Iterate Over Selected Elements

Summary: in this tutorial, you will learn how to iterate over selected elements using the forEach() method and for-loop.

After selecting elements using the querySelectorAll() or getElementsByTagName(), you will get a collection of elements as a NodeList.

To iterate over the selected elements, you can use forEach() method (supported by most modern web browsers, not IE) or just use the plain old for-loop.

Using the forEach() method

The following code selects all elements whose CSS class is .note and changes the background color to yellow:

const notes = document.querySelectorAll('.note');

notes.forEach((note) => {
    note.style.backgroundColor = 'yellow';
});Code language: JavaScript (javascript)

Alternatively, you can borrow the forEach() method of the Array object as follows:

[].forEach.call(notes, (note) => {
    note.style.backgroundColor = "yellow";
});Code language: PHP (php)

Using the for loop

The following code uses the for loop to iterate over the selected elements:

const notes = document.querySelectorAll('.note');
const count = notes.length;

for (let i = 0; i < count; i++) {
    notes[i].style.backgroundColor = "yellow";
}Code language: JavaScript (javascript)
Was this tutorial helpful ?