Subscribe

JavaScript loop querySelectorAll results

✍️

We will learn three ways to loop over a querySelectorAll nodeList in Vanilla JavaScript. See the code examples in the Codepen.

4 Dec, 2020 · 2 min read

Let’s talk about JavaScript NodeLists. Node lists are the results of a querySelectorAll() query.

They are not an array, but they look and behave similarly. It can be tricky looping over their items and there are multiple ways to *loop through a NodeList.

This is how the selector looks like:

const items = document.querySelectorAll('li');
console.log(items);

And the result of the JavaScript querySelectorAll is a NodeList object:

JavaScript NodeList

1. Basic for loop

To loop through a result from querySelectorAll you can use the basic for loop. It is by far the best-supported method. It’s well supported on all browsers and recommended if you need to support older browsers.

See the code here:

for (let i = 0; i < items.length; i++) {
  items[i].addEventListener('click', function () {
    console.log(`Text = ${items[i].innerText}`);
  });
}

It’s just not the most modern or visually appealing looping method.

2. for…of loop

We can also use the for...of loop on a NodeList.

for (const item of items) {
  item.addEventListener('click', () => {
    console.log(`2: Text = ${item.innerText}`);
  });
}

The for of loop is supported by all modern browsers and works pretty well on a list of nodes.

3. forEach loop

My all-time favorite loop to use with querySelectorAll is the forEach loop.

It’s the easiest method to use with NodeLists but will only work in modern browsers.

items.forEach((item) => {
  item.addEventListener('click', () => {
    console.log(`3: Text = ${item.innerText}`);
  });
});

This method can be extended by converting the NodeList to an array before.

[].forEach.call(items, function (item) {
  item.addEventListener('click', function () {
    console.log(`3.1: Text = ${item.innerText}`);
  });
});

Or, we can use the spread operator to convert the list into an array:

[...items].forEach((item) => {
  item.addEventListener('click', () => {
    console.log(`3.2: Text = ${item.innerText}`);
  });
});

There you go: Three examples (+ iterations) of how to loop over the querySelectorAll result in Javascript.

See the Code Examples in this Codepen

You can also have a play around with this Codepen.

See the Pen JavaScript loop querySelectorAll results by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter