最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add event listener to each class in an html collection? - Stack Overflow

programmeradmin4浏览0评论

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 collection. When I use .length() it equals zero. how do I iterate through this collection in order to add event listener to each element in this class? is there a way to convert this html collection into an array? here's what i have so far:

var tableElements = document.getElementsByClassName("element");
console.log(tableElements);
console.log(tableElements.length);

for(var i=0;i<tableElements.length;i++){
   tableElements[i].addEventListener("click", dispElementData(this));
} //doesnt work

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 collection. When I use .length() it equals zero. how do I iterate through this collection in order to add event listener to each element in this class? is there a way to convert this html collection into an array? here's what i have so far:

var tableElements = document.getElementsByClassName("element");
console.log(tableElements);
console.log(tableElements.length);

for(var i=0;i<tableElements.length;i++){
   tableElements[i].addEventListener("click", dispElementData(this));
} //doesnt work
Share Improve this question edited Jul 1, 2018 at 7:04 Eddie 26.8k6 gold badges38 silver badges59 bronze badges asked Jul 1, 2018 at 7:03 user10015498user10015498 611 gold badge1 silver badge3 bronze badges 2
  • HTMLCollection is indeed an array-like object and is iterable. Please check the class-name you're targetting. developer.mozilla/en-US/docs/Web/API/HTMLCollection – Shobhit Chittora Commented Jul 1, 2018 at 7:07
  • Possible duplicate of JavaScript click event listener on class – Feras Al Sous Commented Jul 1, 2018 at 7:21
Add a ment  | 

2 Answers 2

Reset to default 11

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);
    });
});

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 pletely 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)

  1. 暂无评论