Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to get queryselector to work with multiple elements with the same classname?
    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...

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
        }
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!