return elements that match specified CSS selector(s)

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 forEach

    If you have a NodeList from querySelectorAll(), you can convert it into an array and then use forEach.

    const elements = document.querySelectorAll('.my-class');
    elements.forEach(element => {
        // Do something with each element
        console.log(element.textContent);
    });
    

    2. Using a traditional for loop

    You can also loop through the NodeList using a traditional for loop:

    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...of

    The for...of loop 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 like forEach:

    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.