Skip to content Skip to sidebar Skip to footer

Enumerate Through Elements Returned By Getelementbyclassname In Javascript

I have the following markups and scripts to simulate a simple calculator HTML: Copy

When using for-in loops, it's

for ( keyinobject )

so it would be

for (var btn in buttons) {
    buttons[btn].addEventListener
}

Solution 2:

document.getElementsByClassName() returns an array like object that is better iterated like this:

var buttons = document.getElementsByClassName("number");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", numberClick, false);
}

You can iterate arrays the way you were (not recommended though because it iterates all enumerable properties not just array elements which can sometimes mess up the code), but if you did, then buttons[btn] would be the object, not btn like you were trying to use.

Post a Comment for "Enumerate Through Elements Returned By Getelementbyclassname In Javascript"