5 different ways to loop over DOM elements in JavaScript

Raymon
13-04-2018

There are a lot of ways to loop over a NodeList Object (List of DOM elements) that is returned by a querySelectorAll method! In this post, I want to share 5 ways.

Let’s start with defining a piece of HTML and a const variable that is searching for multiple elements.

HTML

    <div class="container" id="myContainer">
        <div class="fake-image">
          <h2>Fake image</h2>
        </div>
        <div class="fake-image">
          <h2>Fake image</h2>
        </div>
        <div class="fake-image">
          <h2>Fake image</h2>
        </div>
        <div class="fake-image">
          <h2>Fake image</h2>
        </div>
    </div>

JavaScript

    const fakeImages = document.querySelectorAll(".fake-image");

So now we are ready to find out which 5 ways we can use to loop over this cool NodeList Object that is returned by the querySelectorAll method.

If a method gives an option of a callback, then I will use the “Arrow function” for that.

1. For-loop

The most know function to loop over everything is the good old For-loop. This is maybe not the prettiest code but definitely high performed.

So if you need to support older browsers like IE11 or lower and you don’t use a compiler like Babel, than this is your best weapon.

Support: every browser!

    const fakeImages = document.querySelectorAll(".fake-image");
    for (var i = 0; i < fakeImages.length; i++) {
      console.log('fakeImage: ', fakeImages[i]);
    }

2. For..of

I would call the For..of loop an extension on the normal For-loop. This is because this function can loop over iterable objects (including String, Array, Array-like arguments, NodeList Objects, TypedArray, Map and Set).

If you need to support old browsers then you definitely need a compiler like Babel. But if you only need to support the modern browsers For..of would be my weapon of choice!

Support: All modern browsers! Not supported in IE11 or lower.

    const fakeImages = document.querySelectorAll(".fake-image");
    for (const fakeImage of fakeImages) {
      console.log('fakeImage: ', fakeImage);
    }

3. For..of entries, keys, values

In a previous way, we just used the NodeList to loop over in the For..of loop. But the NodeList has also a few more methods to use in this loop.

The entries(), keys() and values() methods return a iterator. A iterator is a new iterable protocol in the ES2015 specification.

In JavaScript, some types of data (Array or Map) have built-in functionality to loop over.

Object doesn’t have built-in functionality to loop over it. Via the iterator protocol, we can loop over data types that don’t default support for that.

entries

Each item in this loop is an Array with first the key and then the element. This looks maybe a bit funny but is expected behavior.

    const fakeImages = document.querySelectorAll(".fake-image");
    for (const fakeImage of fakeImages.entries()) {
      console.log('fakeImage: ', fakeImage);
    };

values

Where the entries method gives us an Array of the key and value. Each item in this loop is an element, in other words, the value as the method name tells us.

    const fakeImages = document.querySelectorAll(".fake-image");
    for (const fakeImage of fakeImages.values()) {
      console.log('fakeImage: ', fakeImage);
    };

keys

Just like the values method gives us the value of each item in the NodeList, the keys method gives us the keys from the NodeList Object.

    const fakeImages = document.querySelectorAll(".fake-image");
    for (const fakeImage of fakeImages.keys()) {
      console.log('fakeImage: ', fakeImage);
    };

4. forEach

Here comes a cool method that I was not aware of ?. Just like the Array method forEach, a NodeList Object has its own forEach method.

The most important note on this is that it’s only supported in modern browsers. For support in older browsers, you definitely need a compiler.

Support: All modern browsers! Not supported in IE11 or lower.

    const fakeImages = document.querySelectorAll(".fake-image");
    fakeImages.forEach(fakeImage => {
      console.log('fakeImage: ', fakeImage);
    });

5. (ES2015) Spread syntax with forEach

In the ES2015 we have the Spread syntax for Arrays. With this syntax, you can do a lot of cool stuff! One of those things is, turn a NodeList Object into an Array and use the Array forEach method on it.

For support in older browsers, you definitely need a compiler, because the support is not completely implemented in all the modern browsers.

Support: Almost all modern browsers! Not supported in IE11 or lower.

    const fakeImages = document.querySelectorAll(".fake-image");
    [...fakeImages].forEach(fakeImage => {
            console.dir(fakeImage);
    });

LEAVE A REPLY

you might also like