javascripthtmlfunctionqueryselector

I'm trying to select multiple elements with the queryselectorall but it seems not working and i don't know why


I've tried the queryselector and it selects the first element. I've also tried this using a for loop but it didn't worked too, maybe I have been doing it wrong. Can someone help me with this?

<html>
<body>
    <div id="list">
      <div id="item1" class="bttn">Apple</div>
      <div id="item2" class="bttn">Mango</div>
      <div id="item3" class="bttn">Banana</div>
      <div id="item4" class="bttn">Kiwi</div>
    </div>
<style> 

.bttn{
  display: flex;
  cursor: pointer;
} 

</style>
<script>
  var list = document.querySelectorAll(".bttn");
  console.log(list);
  list.onclick = function(){
    this.style.background = "red";
  };
</script>
</body>
</html>

Solution

  • You need to loop through your collection and apply the click listener to each matching element, and access that element inside the handler with event.target

    <script>
      var list = document.querySelectorAll(".bttn");
      console.log(list);
      list.forEach(el => el.addEventListener('click', function(e){
        e.target.style.background = "red";
      }))
    </script>
    

    You could abstract out the listener function if desired

    <script>
      let list = document.querySelectorAll(".bttn");
      const onBttnClick = (e) => {
        e.target.style.background = "red";
      }
      list.forEach(el => el.addEventListener('click', onBttnClick))
    </script>