How to loop through NodeList returned by querySelectorAll()?
Answers:
When you use
querySelectorAll()in JavaScript, it returns aNodeListof 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...ofLoopThe
for...ofloop allows you to iterate over iterable objects likeNodeListsdirectly:const elements = document.querySelectorAll('.my-class'); for (const element of elements) { console.log(element); // Do something with each element }3. Using a Traditional
forLoopYou can also use a traditional
forloop 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...ofloop are the most straightforward approaches for iterating overNodeListelements since they are concise and easy to read. However, if you need the flexibility of array methods, converting theNodeListto an array is the way to go.