Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”

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=>{

Leave a Comment