How can I loop through elements selected by querySelectorAll()?
Answers:
You can loop through elements selected by
querySelectorAll()in JavaScript using various methods. Here are a few common approaches:1. Using
forEachIf you have a NodeList from
querySelectorAll(), you can convert it into an array and then useforEach.const elements = document.querySelectorAll('.my-class'); elements.forEach(element => { // Do something with each element console.log(element.textContent); });2. Using a traditional
forloopYou can also loop through the NodeList using a traditional
forloop:const elements = document.querySelectorAll('.my-class'); for (let i = 0; i < elements.length; i++) { // Do something with each element console.log(elements[i].textContent); }3. Using
for...ofThe
for...ofloop can also iterate over the NodeList directly:const elements = document.querySelectorAll('.my-class'); for (const element of elements) { // Do something with each element console.log(element.textContent); }4. Using
Array.from()You can convert the NodeList into an array using
Array.from()and then utilize array methods likeforEach:const elements = document.querySelectorAll('.my-class'); Array.from(elements).forEach(element => { // Do something with each element console.log(element.textContent); });5. Using the Spread Operator
You can use the spread operator to convert the NodeList into an array:
const elements = document.querySelectorAll('.my-class'); [...elements].forEach(element => { // Do something with each element console.log(element.textContent); });Any of these methods will allow you to effectively loop through the elements selected by
querySelectorAll(). Choose the one that you find most readable and fits best within your code style.