How to add event listener to each class in an html collection?

前端 未结 2 414
时光说笑
时光说笑 2021-01-17 07:24

I\'m attempting to get all elements by the class of \'element\' and adding an event listener to each of them. however, getElementsByClassName() returns and html

相关标签:
2条回答
  • 2021-01-17 07:38

    You could use document.querySelectorAll(".element") instead. This will use CSS selectors to query the dom (in this case the class "element").

    var tableElements = document.querySelectorAll(".element");
    
    tableElements.forEach(function(element) {
        element.addEventListener("click", function() {
            dispElementData(this);
        });
    });
    
    0 讨论(0)
  • 2021-01-17 07:42

    Sorry! My code above works fine! Turns out that my JS code was executing before the DOM was done loading. Thanks for the the help. The solution was to add an evt listener document object and then call the function once it was completely loaded:

    document.addEventListener("DOMContentLoaded", function(){
                      var tableElements = document.getElementsByClassName("element");  
                 for(var i=0;i<tableElements.length;i++){ 
                    tableElements[i].addEventListener("click", dispElementData(this)); 
                  }
    })
    
    0 讨论(0)
提交回复
热议问题