return elements that match specified CSS selector(s)

How to iterate over elements returned by querySelectorAll()?

Answers:

  • In JavaScript, the querySelectorAll() method returns a static NodeList of elements that match the specified selector string. Since a NodeList is similar to an array, you can iterate over its elements using various methods. Here are a few common ways to do this:

    1. Using a forEach Loop

    You can use the forEach method that is available on NodeLists in modern browsers.

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

    2. Using a Traditional for Loop

    You can also use a traditional for loop to iterate through the NodeList.

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

    3. Using for...of Loop

    The for...of loop is another concise way to iterate over the elements.

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

    4. Converting to an Array

    If you need array methods that are not available on NodeLists, you can convert the NodeList to an array using Array.from() or the spread operator.

    Using Array.from()

    const elements = document.querySelectorAll('.some-class');
    const elementsArray = Array.from(elements);
    elementsArray.forEach(element => {
      console.log(element); // do something with each element
    });
    

    Using the Spread Operator

    const elements = document.querySelectorAll('.some-class');
    const elementsArray = [...elements];
    elementsArray.forEach(element => {
      console.log(element); // do something with each element
    });
    

    These methods provide a flexible way to work with a NodeList returned by querySelectorAll().

Related Questions: