2

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
Eddie
  • 26,593
  • 6
  • 36
  • 58
user10015498
  • 61
  • 1
  • 1
  • 3
  • HTMLCollection is indeed an array-like object and is iterable. Please check the class-name you're targetting. https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection – Shobhit Chittora Jul 01 '18 at 07:07
  • Possible duplicate of [JavaScript click event listener on class](https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class) – Feras Al Sous Jul 01 '18 at 07:21

2 Answers2

9

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);
    });
});
Jonas
  • 829
  • 7
  • 18
2

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)); 
              }
})
user10015498
  • 61
  • 1
  • 1
  • 3