1

I was trying to combine querySelectorAll and matches() to add even listener like this:

HTML

<div id="bkLst" class="dropdown-menu">
    <button class="dropdown-item" type="button" data-b="Book 1">Book 1</button>
    <button class="dropdown-item" type="button" data-b="Book 2">Book 2</button>
    <button class="dropdown-item" type="button" data-b="Book 12">Book 12</button>
</div>

JS

document.addEventListener("click", function(e){
    if(e.target.querySelectorAll.matches("#bkLst button")){
         ...
    }
});

But to no avail. What am I missing?

santa
  • 12,234
  • 49
  • 155
  • 255

3 Answers3

2
let list = document.getElementById('bkLst');

let elements = list.querySelectorAll('.dropdown-item');

for(let element of elements){

   element.addEventListener('click', function() {

       console.log('iyeah')

    });
}
Met Br
  • 634
  • 5
  • 9
2

First you can select the buttons with const elButtons = document.querySelectorAll("#bkLst button"), and loop over the buttons and add event listener like following

elButtons.forEach(el => {
  el.addEventListener("click", () => {
    //do something
  }
})
vecume
  • 46
  • 1
  • 4
1

If you are attempting to create delegated event handling, similar to Jquery, then you only need to do e.target.matches with your selector, matches is meant to be called on a single element, not a collection. Please see my code snippet and related documentation: Element.matches, there are other posts on Stack Overflow which relate to native javascript version(s) of Jquery's delegate event handling, here's one for example - native-js-equivalent-to-jquery-delegation

document.addEventListener("click", function(e){
    if(e.target.matches("#bkLst button")){
         console.log("I'm button:" + e.target.textContent);
    }
});
<div id="bkLst" class="dropdown-menu">
    <button class="dropdown-item" type="button" data-b="Book 1">Book 1</button>
    <button class="dropdown-item" type="button" data-b="Book 2">Book 2</button>
    <button class="dropdown-item" type="button" data-b="Book 12">Book 12</button>
</div>
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40