最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

onclick - Javascript - On click, check if element has an attribute with value - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

Use 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...
}
发布评论

评论列表(0)

  1. 暂无评论