Skip to content
Advertisement

Iterating over result of getElementsByClassName using Array.forEach

I want to iterate over some DOM elements, I’m doing this:

JavaScript

but I get an error:

document.getElementsByClassName(“myclass”).forEach is not a function

I am using Firefox 3 so I know that both getElementsByClassName and Array.forEach are present. This works fine:

JavaScript

Is the result of getElementsByClassName an Array? If not, what is it?

Advertisement

Answer

No, it’s not an array. As specified in DOM4, it’s an HTMLCollection (in modern browsers, at least. Older browsers returned a NodeList).

In all modern browsers (pretty much anything other IE <= 8), you can call Array’s forEach method, passing it the list of elements (be it HTMLCollection or NodeList) as the this value:

JavaScript

If you’re in the happy position of being able to use ES6 (i.e. you can safely ignore Internet Explorer or you’re using an ES5 transpiler), you can use Array.from:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement