return elements that match specified CSS selector(s)

How do I filter elements selected by querySelectorAll() based on certain criteria?

Answers:

  • You can filter elements selected by querySelectorAll() using various methods in combination with JavaScript's array methods. The querySelectorAll() method returns a NodeList of elements that match the specified selector. To filter these elements, you can convert the NodeList to an array and then use the filter() method to apply your criteria.

    Here’s a step-by-step approach to achieving this:

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

    Here’s an example. Suppose you want to filter all <div> elements that have a specific class and certain text content:

    Example:

    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="other">Item 3</div>
    <div class="item">Item 4</div>
    
    // Step 1: Select all div elements with class 'item'
    const items = document.querySelectorAll('div.item');
    
    // Step 2: Convert NodeList to Array
    const itemsArray = Array.from(items);
    
    // Step 3: Filter the elements based on certain criteria
    const filteredItems = itemsArray.filter(item => {
        // For example, filter items that contain '1' in their textContent
        return item.textContent.includes('1');
    });
    
    // Now, filteredItems will only contain the div with 'Item 1'
    console.log(filteredItems); // Output: [<div class="item">Item 1</div>]
    

    Using Array.prototype.slice

    Alternatively, if you prefer not to use Array.from, you can also convert a NodeList to an array using Array.prototype.slice:

    const itemsArray = Array.prototype.slice.call(items);
    

    Summary

    In summary, to filter elements selected using querySelectorAll():

    1. Use querySelectorAll() to get the NodeList of elements.
    2. Convert the NodeList to an array.
    3. Use the filter() method to apply your filtering criteria.

Related Questions: