return elements that match specified CSS selector(s)

How do I iterate through elements selected with querySelectorAll?

Answers:

  • You can iterate through elements selected with querySelectorAll in several ways, as it returns a NodeList. Here are a few common methods you can use:

    1. Using forEach()

    The easiest way, especially if you're targeting modern browsers, is to use the forEach() method available on the NodeList (since NodeList now behaves like an array in most modern browsers):

    const elements = document.querySelectorAll('selector'); // Replace 'selector' with your actual selector
    elements.forEach(element => {
        // Do something with each element
        console.log(element);
    });
    

    2. Using a Traditional for Loop

    You can also use a traditional for loop. This is compatible with all browsers:

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

    3. Using for...of Loop

    Another modern approach is using the for...of loop, which works well with iterable objects like NodeLists:

    const elements = document.querySelectorAll('selector'); // Replace 'selector' with your actual selector
    for (const element of elements) {
        // Do something with each element
        console.log(element);
    }
    

    4. Using Array.from()

    If you prefer to convert the NodeList into an array (for example, to use array methods like map, filter, etc.), you can use Array.from():

    const elements = document.querySelectorAll('selector'); // Replace 'selector' with your actual selector
    const elementsArray = Array.from(elements);
    
    elementsArray.forEach(element => {
        // Do something with each element
        console.log(element);
    });
    

    Example Usage

    Suppose you want to change the background color of all <div> elements with a class of .item:

    const items = document.querySelectorAll('div.item');
    
    items.forEach(item => {
        item.style.backgroundColor = 'lightblue';
    });
    

    Choose the method that best suits your situation and browser compatibility needs!

Related Questions: