How to loop through NodeList returned by querySelectorAll()?
Answers:
When you use
querySelectorAll()
in JavaScript, it returns aNodeList
of elements that match the specified selector. To loop through thisNodeList
, you have several options. Here are some of the most common methods:1. Using
forEach()
If you use a modern browser, you can use the
forEach()
method directly on theNodeList
:const elements = document.querySelectorAll('.my-class'); elements.forEach(element => { console.log(element); // Do something with each element });
2. Using a
for...of
LoopThe
for...of
loop allows you to iterate over iterable objects likeNodeLists
directly:const elements = document.querySelectorAll('.my-class'); for (const element of elements) { console.log(element); // Do something with each element }
3. Using a Traditional
for
LoopYou can also use a traditional
for
loop to iterate through theNodeList
:const elements = document.querySelectorAll('.my-class'); for (let i = 0; i < elements.length; i++) { console.log(elements[i]); // Do something with each element }
4. Converting to an Array (if needed)
If you need to use array methods that are not available on
NodeList
, you can convert it to an array usingArray.from()
or the spread operator:// Using Array.from() const elements = document.querySelectorAll('.my-class'); const elementsArray = Array.from(elements); elementsArray.forEach(element => { console.log(element); // Do something with each element }); // Using the spread operator const elementsArray2 = [...elements]; elementsArray2.forEach(element => { console.log(element); // Do something with each element });
Conclusion
In modern JavaScript, using
forEach()
or afor...of
loop are the most straightforward approaches for iterating overNodeList
elements since they are concise and easy to read. However, if you need the flexibility of array methods, converting theNodeList
to an array is the way to go.