Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  56] [ 6]  / answers: 1 / hits: 101823  / 10 Years ago, tue, june 17, 2014, 12:00:00

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>




More From » foreach

 Answers
3

That's because document.getElementsByClassName returns a HTMLCollection, not an array.



Fortunately it's an array-like object (which explains why it's logged as if it was an object and why you can iterate with a standard for loop), so you can do this :



[].forEach.call(document.getElementsByClassName('myClass'), function(v,i,a) {


With ES6 (on modern browsers or with Babel), you may also use Array.from which builds arrays from array-like objects:



Array.from(document.getElementsByClassName('myClass')).forEach(v=>{


or spread the array-like object into an array:



[...document.getElementsByClassName('myClass'))].forEach(v=>{

[#70536] Sunday, June 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;