JavaScript loop querySelectorAll results
permalinkLet'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:
1. Basic for loop permalink
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 permalink
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 permalink
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 permalink
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! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter