return elements that match specified CSS selector(s)

How do you loop through elements selected by querySelectorAll()?

Answers:

  • You can loop through the elements selected by querySelectorAll() in various ways in JavaScript. Here are some common methods:

    1. Using forEach with NodeList

    The result of querySelectorAll() is a NodeList, and you can use the forEach method directly if you're not concerned about compatibility with very old browsers.

    const elements = document.querySelectorAll('.my-elements');
    elements.forEach((element) => {
        // Perform operations on each element
        console.log(element.textContent);
    });
    

    2. Using a for loop

    You can convert the NodeList to an array and then use a standard for loop:

    const elements = document.querySelectorAll('.my-elements');
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        // Perform operations on each element
        console.log(element.textContent);
    }
    

    3. Using for...of loop

    The for...of loop allows you to iterate over iterable objects, including NodeLists:

    const elements = document.querySelectorAll('.my-elements');
    for (const element of elements) {
        // Perform operations on each element
        console.log(element.textContent);
    }
    

    4. Using Array.from()

    If you prefer to work with array methods, you can convert the NodeList into an array using Array.from():

    const elements = document.querySelectorAll('.my-elements');
    const elementsArray = Array.from(elements);
    
    elementsArray.forEach((element) => {
        // Perform operations on each element
        console.log(element.textContent);
    });
    

    Summary

    Any of these methods will allow you to loop through the elements selected by querySelectorAll(). Choose the one that you find most readable or that best fits your coding style!

Related Questions: