return elements that match specified CSS selector(s)

How do I filter elements from NodeList returned by querySelectorAll()?

Answers:

  • When you use document.querySelectorAll(), it returns a NodeList, which is a collection of elements that match the specified selector. While a NodeList behaves like an array in some contexts, it doesn't have all the array methods. To filter elements from a NodeList, you can convert it into an actual array and then use Array.prototype.filter().

    Here's how you can do it:

    Using Array.from()

    You can convert the NodeList into an array using Array.from() and then apply the filter method:

    const nodeList = document.querySelectorAll('your-selector');
    const filteredElements = Array.from(nodeList).filter(element => {
        // Your filtering condition
        return element.classList.contains('your-class'); // Example condition
    });
    

    Using the Spread Operator

    Another way to convert the NodeList to an array is to use the spread operator (...):

    const nodeList = document.querySelectorAll('your-selector');
    const filteredElements = [...nodeList].filter(element => {
        // Your filtering condition
        return element.classList.contains('your-class'); // Example condition
    });
    

    Example

    Here's a complete example demonstrating how to filter elements based on a condition:

    <div class="item"></div>
    <div class="item special"></div>
    <div class="item"></div>
    <div class="item special"></div>
    
    <script>
      const nodeList = document.querySelectorAll('.item');
      const filteredElements = Array.from(nodeList).filter(element => {
          return element.classList.contains('special');
      });
    
      console.log(filteredElements); // This will contain only the elements with the class 'special'
    </script>
    

    Summary

    In summary, to filter elements from a NodeList:

    1. Convert the NodeList into an array using either Array.from() or the spread operator.
    2. Use the filter() method with your filtering condition to get the desired elements.