return elements that match specified CSS selector(s)

How does querySelectorAll() work in JavaScript?

Answers:

  • The querySelectorAll() method in JavaScript is used to select all elements in the document that match a specified CSS selector or a group of selectors. It returns a static NodeList of all matching elements. Here’s how it works:

    Syntax

    const elements = document.querySelectorAll(selector);
    
    • selector: A string containing one or more CSS selectors separated by commas.

    Return Value

    • The method returns a NodeList, which is a collection of DOM elements. Unlike an array, a NodeList does not have all the array methods, but you can iterate over it using forEach, or convert it into an array using Array.from() or the spread operator ([...]).

    Key Points

    1. CSS Selector Syntax: You can use any valid CSS selector, including IDs, classes, tag names, attribute selectors, pseudo-classes, and more. For example:

      • Single class: ".className"
      • Multiple classes: ".class1.class2"
      • ID: "#idName"
      • Element: "div"
      • Attribute: "[type='text']"
      • Combinations: "div > .className, .otherClass"
    2. Static NodeList: The NodeList returned by querySelectorAll() is static, meaning it will not automatically update if the DOM changes after the selection (unlike a live NodeList returned by getElementsByTagName or getElementsByClassName).

    3. No Results: If no elements match the selector, querySelectorAll() returns an empty NodeList.

    4. Browser Compatibility: The method is widely supported across modern browsers.

    Example Usage

    Here’s a simple example of how to use querySelectorAll():

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>querySelectorAll Example</title>
    </head>
    <body>
        <div class="example">Item 1</div>
        <div class="example">Item 2</div>
        <div class="example">Item 3</div>
        <div class="another">Item 4</div>
        
        <script>
            // Select all elements with the class "example"
            const items = document.querySelectorAll('.example');
            
            // Iterate over the NodeList and log the text content
            items.forEach((item) => {
                console.log(item.textContent);
            });
        </script>
    </body>
    </html>
    

    Conclusion

    querySelectorAll() is a powerful and flexible method to select multiple elements in the DOM based on CSS selectors. It allows you to easily manipulate or read properties from groups of elements, making it a commonly used tool in web development.

Related Questions: