return elements that match specified CSS selector(s)

How do I iterate over elements returned by querySelectorAll()?

Answers:

  • In JavaScript, the querySelectorAll() method returns a NodeList of elements that match the specified CSS selectors. You can iterate over this NodeList in several ways:

    1. Using forEach()

    The NodeList returned by querySelectorAll() has a forEach method which you can use to iterate over each element.

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

    2. Using a for loop

    You can also convert the NodeList to an array and use a traditional for loop.

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

    3. Using the for...of loop

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

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

    4. Converting to an Array

    You can convert the NodeList to an array using Array.from() or the spread operator [...NodeList] and then use any array iteration method.

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

    Choose the method that suits your needs best, but using forEach() is a common and concise way to handle NodeLists directly.

Related Questions: