JS: iterating over result of getElementsByClassName using Array.forEach

JS: iterating over result of getElementsByClassName using Array.forEach

I want to iterate over some DOM elements, I’m doing this:
document.getElementsByClassName( “myclass” ).forEach( function(element, index, array) {
//do stuff

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:
[2, 5, 9].forEach( function(element, index, array) {
//do stuff

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


Solution 1:

No. 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:

var els = document.getElementsByClassName("myclass");

Array.prototype.forEach.call(els, function(el) {
    // Do stuff here

// Or
[].forEach.call(els, function (el) {...});

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:

Array.from(els).forEach((el) => {
    // Do stuff here

Solution 2:

You can use Array.from to convert collection to array, which is way cleaner than Array.prototype.forEach.call:

    function(element, index, array) {
        // do stuff

In older browsers which don’t support Array.from, you need to use something like Babel.

Related:  Don't make functions within a loop [duplicate]

ES6 also adds this syntax:

    (element, index, array) => {
        // do stuff

Rest destructuring with ... works on all array-like objects, not only arrays themselves, then good old array syntax is used to construct an array from the values.

While the alternative function querySelectorAll (which kinda makes getElementsByClassName obsolete) returns a collection which does have forEach natively, other methods like map or filter are missing, so this syntax is still useful:

    (element, index, array) => {
        // do stuff

[...document.querySelectorAll(".myclass")].map(element => element.innerHTML);

Solution 3:

Or you can use querySelectorAll which returns NodeList:


Supported by modern browsers (including Edge, but not IE):
Can I use querySelectorAll

MDN: Document.querySelectorAll()

Solution 4:

Edit: Although the return type has changed in new versions of HTML (see Tim Down’s updated answer), the code below still works.

As others have said, it’s a NodeList. Here’s a complete, working example you can try:

<!DOCTYPE html>
        <meta charset="UTF-8">
            function findTheOddOnes()
                var theOddOnes = document.getElementsByClassName("odd");
                for(var i=0; i<theOddOnes.length; i++)
        <h1>getElementsByClassName Test</h1>
        <p class="odd">This is an odd para.</p>
        <p>This is an even para.</p>
        <p class="odd">This one is also odd.</p>
        <p>This one is not odd.</p>
            <input type="button" value="Find the odd ones..." onclick="findTheOddOnes()">

This works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

Related:  Keep getting “tsc.exe” exited with code 1

Solution 5:

Is the result of getElementsByClassName an Array?


If not, what is it?

As with all DOM methods that return multiple elements, it is a NodeList, see https://developer.mozilla.org/en/DOM/document.getElementsByClassName

Solution 6:

The result of getElementsByClassName() is not an Array, but an array-like object. Specifically it’s called an HTMLCollection, not to be confused with NodeList (which has it’s own forEach() method).

One simple way with ES2015 to convert an array-like object for use with Array.prototype.forEach() that hasn’t been mentioned yet is to use the spread operator or spread syntax:

const elementsArray = document.getElementsByClassName('myclass');

[...elementsArray].forEach((element, index, array) => {
    // do something