0

What's the proper way to use the querySelectorAll method? I'm just trying to add a click event to each div with class '.box', but it's not working. I've found that this works fine if I replace the method with 'getElementById' and just test the kitchen box.

document.querySelectorAll('.box').addEventListener('click', test);

function test() {
  console.log('hi');
}
<section class="main">
  <div class="box" id="kitchen"></div>
  <div class="box" id="laundry"></div>
  <div class="box" id="bedroom"></div>
</section>
David Skx
  • 131
  • 8

2 Answers2

1

It's really simple, you just loop over every element and add an event listener.

document.querySelectorAll('.box').forEach(item => {
  item.addEventListener('click', event => {
    // Handle the click event here
  })
})
Akar
  • 5,075
  • 2
  • 25
  • 39
0

document.querySelectorAll() returns an NodeList object which you can treat as an array. You have to loop on every element and add event listener on every one of them separately.

USHKA
  • 647
  • 4
  • 18