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?

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
    console.log(el.tagName);
});

// 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
    console.log(el.tagName);
});

How do I use .forEach on DOM Elements? - DEV, Figuring out how to loop through a NodeList. Tagged with todayisearched, javascript. getElementsByClassName("utc-time"); timestamps. Although NodeList is not an Array, it is possible to iterate on it using forEach() . Iterating Over Result Of getElementsByClassName Using Array forEach - iterating-with-getelementsbyclassname-and-foreach.js

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

Array.from(document.getElementsByClassName("myclass")).forEach(
    function(element, index, array) {
        // do stuff
    }
);

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


ES6 also adds this syntax:

[...document.getElementsByClassName("myclass")].forEach(
    (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:

[...document.querySelectorAll(".myclass")].map(
    (element, index, array) => {
        // do stuff
    }
);

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

Iterating Over Result Of getElementsByClassName Using Array , Iterating Over Result Of getElementsByClassName Using Array forEach. iterating -with-getelementsbyclassname-and-foreach.js. var els = document. Pas de. Comme spécifié dans DOM4 , c'est un HTMLCollection (dans les navigateurs modernes, au moins. Les navigateurs plus anciens ont retourné un NodeList).. dans tous les navigateurs modernes (à peu près tout autre IE = 8), Vous pouvez appeler la méthode forEach de Array, en lui passant la liste des éléments (que ce soit HTMLCollection ou NodeList) comme la valeur this:

Or you can use querySelectorAll which returns NodeList:

document.querySelectorAll('.myclass').forEach(...)

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

MDN: Document.querySelectorAll()

HTMLCollection forEach loop, Ever had an array-like object that you want to iterate over? class and we query for a HTMLCollection using 'getElementsByClassName'. Definition and Usage. The forEach() method calls a function once for each element in an array, in order.. Note: the function is not executed for array elements without values.

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>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            function findTheOddOnes()
            {
                var theOddOnes = document.getElementsByClassName("odd");
                for(var i=0; i<theOddOnes.length; i++)
                {
                    alert(theOddOnes[i].innerHTML);
                }
            }
        </script>
    </head>
    <body>
        <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>
        <form>
            <input type="button" value="Find the odd ones..." onclick="findTheOddOnes()">
        </form>
    </body>
</html>

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

javascript, javascript - JS: iterating over result of getElementsByClassName using Array. forEach forEach( function(element, index, array) { //do stuff });. but I get an error: � We'll also see some techniques used in browsers that don't support iterating over a NodeList using forEach() and how to convert a NodeList to an Array using the Array.from() method. querySelector and querySelectorAll are DOM APIs available on modern web browsers. They are used to query DOM elements that match a CSS selector.

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
});

How to correctly iterate through getElementsByClassName, JS: iterating over result of getElementsByClassName using Array , tagName); }); // Or [].forEach.call(els, function (el) {}); If you're in the happy position of being� JavaScript Array forEach; Lodash forEach; jQuery each() Iterating Over an Associative Array; Summary; As the language has matured so have our options to loop over arrays and objects. JavaScript objects are also arrays, which makes for a clean solution to index values by a key or name. The Basic For Loop. JavaScript for loops iterate over each

For loop for HTMLCollection elements, javascript loop through dom elements htmlcollection concat iterate htmlcollection foreach getElementsByClassName("events"); console.log(list[0].id); for (key in list) Why is the second console output undefined but the first console output is So, to get the value from the pseudo-array, you'd have to do list[key] and to get � The array forEach() was called upon. thisArg Optional Value to use as this when executing callback. Return value. undefined. Description. forEach() calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized. (For sparse arrays, see

How to iterate through all selected elements into an array , getElementsByClassName( "element-class");; Finding HTML Loop through the all the div elements using the forEach() method. Output: Before clicking on the button: After clicking on the button: way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff. Let’s look at some options for iterating over a NodeList, as you get back from running a document.querySelectorAll. We’ve written an updated article about this: A Bunch of Options for Looping Over querySelectorAll NodeLists. Not all browsers support forEach on NodeLists, but for those that do:

The intuitive and powerful forEach loop in JavaScript – clubmate.fi, forEach loops in JavaScripts are pretty great, here's how to use them with arrays, nodeLists, Filed under: JavaScript—Tags: array, forEach, loop getElementsByClassName('module'), // You have to call the arrays forEach method Array.prototype. Stops the loop when the counter hits 3 console.log(' Yup, over three'); }. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

Comments
  • No need to convert it to an Array first. Just use [].forEach.call(elsArray, function () {...}).
  • It's NOT a NodeList. It's an array-like object. I don't even think it has an instance type. querySelectorAll method returns a NodeList though.
  • @MaksimVi. You're absolutely right: DOM4 specifies that document.getElementsByClassName() should return an HTMLCollection (which is very similar but not a NodeList). Thanks for pointing out the mistake.
  • @MaksimVi.: I wonder whether that changed at some point. I usually check these things.
  • @TimDown, Thanks for HTMLCollection tip. Now I finally can use HTMLCollection.prototype.forEach = Array.prototype.forEach; in my code.
  • Note: without transpilling as suggested (Babel), this is NOT compatible in IE < Edge, Opera, Safari < 9, Android browser, Chrome for Android, ...etc) Source: mozilla dev docs
  • Bear in mind the performance penalty over getElementByClassName
  • The performance penalty is negligible compared to other more intensive tasks like modifying DOM. If I execute 60,000 of these in 1 millisecond, I'm pretty sure it won't be an issue for any reasonable usage :)
  • You linked the wrong benchmark. Here is the correct one measurethat.net/Benchmarks/Show/4076/0/… Just ran it on my low-end phone, got 160k/s vs 380k/s. Since you mentioned DOM manipulation, here is that too measurethat.net/Benchmarks/Show/5705/0/… Got 50k/s vs 130k/s. As you see it's even slower to manipulate DOM, likely due to NodeList being static (as mentioned by others). Still neglegible in most use cases, but almost 3 fold slower nonetheless.
  • I feel this is really the right way to do it in modern browsers. This is the exact use case spread syntax was created to solve.
  • Chrome 49 return forEach in not a function
  • @VitalyZdanevich Try Chromium 50
  • On Chrome 50 I am getting document.querySelectorAll(...).forEach is not a function