0
    let myvariable = document.querySelectorAll('.my-button');
    
    myvariable.addEventListener('click', function (e) {
      var button = e.target;
      
      if (button.getAttribute('data-reset') === 'true') {
        // Reset the filters
        var filter = button.getAttribute('data-filter');
        resetFilter(filter);
      } else {
        // Filter the tag
        var filter = button.getAttribute('data-filter');
        var tag    = button.getAttribute('data-filter-tag');
        filterTag(filter, tag);
      }
    });

This is what I have.

I have multiple my-buttons, like so:

    <button class="my-button"></button> <-- works
    <button class="my-button"></button> <-- does not work
    <button class="my-button"></button> <-- does not work

And I want all of them to be targeted for the addEventListener. The problem? Only the first button works, the rest does not seem to work.

What am I doing wrong?

Note, I also tried getElementsByClassName. but that also failed...

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
Johan
  • 883
  • 1
  • 9
  • 24
  • 1
    Does this answer your question? [addEventListener on a querySelectorAll() with classList](https://stackoverflow.com/questions/50643302/addeventlistener-on-a-queryselectorall-with-classlist) – lusc Dec 19 '21 at 12:30
  • I tried adding a foreach, but that also failed... perhaps I did it wrong? It gives me different errors per type. – Johan Dec 19 '21 at 12:31
  • 2
    @Johan Can you please show your attempt with `.forEach()`? The current code crashes and doesn't do what you're describing (no buttons work) – Nick Parsons Dec 19 '21 at 12:32

1 Answers1

1

Attach event listener to all the buttons using forEach

Try like this

Array.from(document.querySelectorAll('.my-button')).forEach(item => {
    item.addEventListener('click', function(e) {
        var button = e.target;

        if (button.getAttribute('data-reset') === 'true') {
            // Reset the filters
            var filter = button.getAttribute('data-filter');
            resetFilter(filter);
        } else {
            // Filter the tag
            var filter = button.getAttribute('data-filter');
            var tag = button.getAttribute('data-filter-tag');
            filterTag(filter, tag);
        }
    });
});
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
  • Is there a way I can make it 'unclicked' if I choose another button? Now, all results are gone if I click one button and I want to choose the other button... – Johan Dec 19 '21 at 12:44