return elements that match specified CSS selector(s)

How do I filter elements from a NodeList returned by querySelectorAll?

Answers:

  • In JavaScript, when you use document.querySelectorAll(), it returns a NodeList containing all matching elements. If you want to filter the elements in this NodeList, you can convert it to an array and then use array methods like filter(). Here's how to do it:

    1. Convert the NodeList to an array using Array.from() or the spread operator [...].
    2. Use the filter() method to filter the elements based on your criteria.

    Example: Filtering Elements from a NodeList

    // Let's say you want to select all <div> elements and filter those that have a specific class
    const divs = document.querySelectorAll('div');
    
    // Convert NodeList to an array
    const divArray = Array.from(divs);
    
    // Filter to get only the divs that have the class 'active'
    const activeDivs = divArray.filter(div => div.classList.contains('active'));
    
    // Now 'activeDivs' contains only the div elements with the class 'active'
    console.log(activeDivs);
    

    Using the Spread Operator

    Alternatively, you can achieve the same result using the spread operator:

    // Select all <div> elements
    const divs = document.querySelectorAll('div');
    
    // Filter directly using the spread operator
    const activeDivs = [...divs].filter(div => div.classList.contains('active'));
    
    // Output the active divs
    console.log(activeDivs);
    

    Summary

    To filter elements from a NodeList:

    1. Convert the NodeList into an array using Array.from() or the spread operator [...nodeList].
    2. Use the filter() method to create a new array with only the elements that meet your criteria.

Related Questions: