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

前端 未结 2 435
时光说笑
时光说笑 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条回答
  •  萌比男神i
    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);
        });
    });
    

提交回复
热议问题