return elements that match specified CSS selector(s)

How can I use querySelectorAll() to select multiple elements?

Answers:

  • The querySelectorAll() method in JavaScript is a powerful way to select multiple elements from the DOM based on CSS selectors. It returns a NodeList of all elements that match the specified selector(s). Here's how you can use it:

    Basic Syntax

    const elements = document.querySelectorAll('selector');
    
    • Replace 'selector' with your desired CSS selector.

    Selecting Multiple Elements

    You can select multiple elements by using various selectors:

    1. Using Class Selector:

      const items = document.querySelectorAll('.my-class');
      

      This selects all elements with the class my-class.

    2. Using Tag Name:

      const paragraphs = document.querySelectorAll('p');
      

      This selects all <p> elements in the document.

    3. Using ID Selector: While IDs should be unique, you can still use the ID selector if you're looking to select a specific element:

      const singleElement = document.querySelectorAll('#my-id'); // This will return a NodeList with 0 or 1 items.
      
    4. Combining Selectors: You can use multiple classes, descendant selectors, pseudo-classes, and more:

      const elements = document.querySelectorAll('div.my-class > p:first-child');
      

      This selects the first <p> child of any <div> that has the class my-class.

    5. Using Multiple Selectors: You can combine different selectors using commas:

      const elements = document.querySelectorAll('.class1, .class2, p');
      

      This selects all elements with class1, all elements with class2, and all <p> elements.

    Working with the NodeList

    The result from querySelectorAll() is a NodeList, which is similar to an array but doesn't have all the array methods. You can loop through the NodeList like this:

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

    Example

    Here’s a complete example where you select multiple elements and change their background color:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box special"></div>
        
        <script>
            const boxes = document.querySelectorAll('.box');
            boxes.forEach(box => {
                box.style.backgroundColor = 'lightblue'; // Change the background color of each box
            });
        </script>
    </body>
    </html>
    

    Conclusion

    querySelectorAll() is a versatile method for selecting multiple DOM elements with a variety of CSS selector syntax. You can combine these selectors to get exactly what you need and then manipulate the selected elements as necessary.

Related Questions: