In my JSFiddle, I’m simply trying to iterate over an array of elements. The array is non-empty, as the log statements prove. Yet the call to forEach gives me the (not so helpful) “Uncaught TypeError: undefined is not a function” error.
I must be doing something stupid; what am I doing wrong?
My code:
var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr.forEach(function(v, i, a) {
console.log(v);
});
.myClass {
background-color: #FF0000;
}
<div class="myClass">Hello</div>
arris not an array, but aHTMLCollection. It doesn't have the same methods as an array. developer.mozilla.org/en-US/docs/Web/API/… . Here's a SO post about it even: stackoverflow.com/questions/13433799/…[1,2,3].forEach(function(v,i,a) { console.log(v); });is fine. What's the difference between this and the array in my example?arr instanceof Arraywill result infalseit cannot avail of any prototype methods of theArrayobject such as Array.prototype.forEach().arris a HTMLCollection and an array like object (but does not inherit from or instantiateArray). Hence your standardforloop will work as that simply iterates through index of the object and is not a prototype ofArray.