5

The button

I want to get it to work with an event listener like this one:

document.body.addEventListener('click', function(e) {
console.log(e.target);
    if (e.target.hasAttribute('data-a-target="popout-chat-button"')) {
            console.log('popout button');
    }
});
<button data-a-target="popout-chat-button" data-test-selector="popout-button">Popout</button>

I can't check the value with hasAttribute, what would be the best approach to do so.

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
oban_internet
  • 209
  • 1
  • 3
  • 11
  • 3
    What about [getAttribute()](https://www.w3schools.com/jsref/met_element_getattribute.asp) ? – bugs Apr 21 '18 at 13:04

3 Answers3

6

Use e.target.getAttribute to get the attribute value of the target element. Then compare that with the value of the attribute you expect in the if condition:

document.body.addEventListener('click', function(e){
    console.log(e.target);
    if(e.target.getAttribute('data-a-target') === "popout-chat-button"){
        console.log('popout button');
    }
});
<button data-a-target="popout-chat-button" data-test-selector="popout-button">Popout</button>

The getAttribute() method returns the value of the attribute with the specified name, of an element.

Syntax

element.getAttribute(attributename)

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
2

You can use:

.dataset: The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM. ...

Instead of:

e.target.hasAttribute('data-a-target="popout-chat-button"')

you can simply write:

e.target.dataset.aTarget == "popout-chat-button"

document.body.addEventListener('click', function(e){
  console.log(e.target.dataset.aTarget);

  if(e.target.dataset.aTarget == "popout-chat-button"){
      console.log('popout button');
  }
});
<button data-a-target="popout-chat-button" data-test-selector="popout-button">Popout</button>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
1

you can user getAttribute function. It returns the value of attribute if it exists otherwise return null.

if(e.target.getAttribute("data-a-target") === "popout-chat-button") {
     // attribute exists and value is equal to what you want...
}
devmarkpro
  • 153
  • 4
  • 13