How to iterate over dom elements - JavaScript

Mo Ibra

Mo Ibra

Jan 6, 2023

In this article we will learn how to iterate over dom elements in JavaScript.

It is very common to iterate over dom elements in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to iterate over dom elements.

We will select a set of buttons through querySelectorAll() method, and then we want to add an event listener, meaning when any of the buttons is pressed, something happens.

// Select Elements
var buttons = document.querySelectorAll('button');

// TODO: iterate over `NodeList` elements and attach a click handler

How to solve this problem?

The solution to this problem is easy and simple, and fortunately we can solve it in more than one way, such as:

  • Using forEach
  • Using spread operator ...
  • Using for .. of
  • Using for loop

Iterate over dom elements using forEach

The easy and simple way is to use forEach to iterate over all elements.

Let's see an example

// Select elements
var buttons = document.querySelectorAll('button');

// Iterate using `forEach`
buttons.forEach(button => {
    // Add event listener to each button
    button.addEventListener('click', function() {
        console.log('Do something');
    })
});

Iterate over elements using spread operator

You can use spread operator to iterate over elements in DOM tree as well.

Let's see an example:

// Select elements
var buttons = document.querySelectorAll('button');

// Iterate using `forEach`
[...buttons].forEach(button => {
    // Add event listener to each button
    button.addEventListener('click', function() {
        console.log('Do something');
    })
});

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. MDN


Iterate over elements using for .. in

We can use for .. in to solve this problem as well.

Example

// Select elements
var buttons = document.querySelectorAll('button');

// Iterate using `forEach`
for(const button of buttons) {
    // Add event listener to each button
    button.addEventListener('click', function() {
        console.log('Do something');
    })
}

Iterate over elements using for loop

We can use for loop to iterate over DOM elements as well.

Example

// Select elements
var buttons = document.querySelectorAll('button');

// Iterate over elements using `for`
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function() {
        console.log('Do something');
    })
}

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: