Want to add “addEventListener” on multiple elements with same class

后端 未结 3 1508
野的像风
野的像风 2020-12-21 03:38

I\'d like to perform the logic in the \"onClick\" through the event listener in jS but it only seems to run once? I have the class in all four but I can\'t figure out why it

3条回答
  •  不知归路
    2020-12-21 04:30

    Need to use querySelectorAll instead of querySelector. And iterate over the list like this.

    const breakdownButton = document.querySelectorAll('.breakdown');
    
    // It add event listeners for the first button element. 
    // you can use forloop or using map function to iterate for the list elements and here i used breakdownButton[0] as an example.
    
    breakdownButton[0].addEventListener('click', function() {
      console.log(this.innerHTML);
    });
    

    Use iterate functions like forEach or map. I used forEach

    const breakdownButton = document.querySelectorAll('.breakdown');
    breakdownButton.forEach(function(btn) {
      btn.addEventListener('click', function() {
        console.log();
      });
    });
    

提交回复
热议问题