How do you iterate over the NodeList returned by querySelectorAll()
?
Answers:
To iterate over a
NodeList
returned by thequerySelectorAll()
method in JavaScript, you have several options. ANodeList
is similar to an array but does not have all the array methods. Here are some common ways to iterate over it:1. Using a
for
loopYou can use a classic
for
loop to iterate over theNodeList
:const nodes = document.querySelectorAll('div'); // Example selector for (let i = 0; i < nodes.length; i++) { console.log(nodes[i]); // Access each node }
2. Using
forEach
If you want to use a more modern approach, you can convert the
NodeList
to an array and use theforEach
method:const nodes = document.querySelectorAll('div'); nodes.forEach(node => { console.log(node); // Access each node });
3. Using
Array.from()
You can also convert the
NodeList
to an array usingArray.from()
:const nodes = document.querySelectorAll('div'); Array.from(nodes).forEach(node => { console.log(node); // Access each node });
4. Using the spread operator
You can convert the
NodeList
to an array using the spread operator (...
):const nodes = document.querySelectorAll('div'); [...nodes].forEach(node => { console.log(node); // Access each node });
5. Using
for...of
loopYou can also use the
for...of
loop, which works directly with iterable objects likeNodeList
:const nodes = document.querySelectorAll('div'); for (const node of nodes) { console.log(node); // Access each node }
Any of these methods will allow you to effectively iterate over the elements in a
NodeList
returned byquerySelectorAll()
. Choose the one that you find most readable and aligns with your coding style!