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
2 Answers
Reset to default 11You 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));
}
})