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>
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.
Share Improve this question edited Apr 21, 2018 at 13:12 Narendra Jadhav 10.3k15 gold badges34 silver badges44 bronze badges asked Apr 21, 2018 at 13:01 oban_internetoban_internet 2291 gold badge3 silver badges12 bronze badges 1- 3 What about getAttribute() ? – bugs Commented Apr 21, 2018 at 13:04
3 Answers
Reset to default 6Use e.target.getAttribute
to get the attribute value of the target element. Then pare 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)
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>
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...
}