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() using various methods in JavaScript. Here are some common ways to do this:

    1. Using a for loop:

    const elements = document.querySelectorAll('.my-class'); // Change .my-class to your selector
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        // Do something with the element
        console.log(element.textContent);
    }
    

    2. Using forEach:

    The NodeList returned by querySelectorAll() does not have a forEach method, but you can convert it to an array using Array.from() or the spread operator:

    const elements = document.querySelectorAll('.my-class');
    
    // Using Array.from
    Array.from(elements).forEach(element => {
        // Do something with the element
        console.log(element.textContent);
    });
    
    // Using the spread operator
    [...elements].forEach(element => {
        // Do something with the element
        console.log(element.textContent);
    });
    

    3. Using for...of loop:

    You can also use the for...of loop, which works directly with any iterable:

    const elements = document.querySelectorAll('.my-class');
    for (const element of elements) {
        // Do something with the element
        console.log(element.textContent);
    }
    

    4. Using map (with conversion to array):

    If you want to create a new array based on the selected elements, you can use the map function after converting to an array:

    const elements = document.querySelectorAll('.my-class');
    const texts = Array.from(elements).map(element => element.textContent);
    console.log(texts); // This will log an array of text contents
    

    Choose any method that fits your use case! Each of them provides a way to loop through the selected elements efficiently.

Related Questions: