return elements that match specified CSS selector(s)

What is querySelectorAll() in JavaScript?

Answers:

  • querySelectorAll() is a method in JavaScript that is used to select and return a list of DOM elements that match a specified CSS selector. This method is part of the Document Object Model (DOM) API and can be called on any DOM element or the document object itself.

    Syntax

    element.querySelectorAll(selector);
    

    or

    document.querySelectorAll(selector);
    

    Parameters

    • selector: A string representing a CSS selector(s) to match the elements. This can include any valid CSS selector, such as element, class, ID selectors, and attribute selectors. Multiple selectors can be separated by commas.

    Return Value

    querySelectorAll() returns a NodeList of matching elements. A NodeList is similar to an array but is not exactly the same; it is a collection of nodes that can be iterated over, but it does not have all the array methods.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>querySelectorAll Demo</title>
    </head>
    <body>
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item special">Item 3</div>
        <div class="item">Item 4</div>
    
        <script>
            // Selecting all elements with the class 'item'
            const items = document.querySelectorAll('.item');
    
            // Loop through the NodeList and log the text content of each item
            items.forEach(item => {
                console.log(item.textContent);
            });
    
            // Selecting all elements with the class 'special'
            const specialItem = document.querySelectorAll('.special');
            console.log(specialItem[0].textContent); // Outputs: Item 3
        </script>
    </body>
    </html>
    

    Key Points

    • querySelectorAll() allows for complex selections using any valid CSS selector syntax.
    • The results returned are a static NodeList, meaning changes to the DOM after calling querySelectorAll() do not affect the returned list.
    • To convert a NodeList to an array, you can use Array.from() or the spread operator [...].

    Usage

    This method is widely used for manipulating groups of elements on the webpage, such as applying styles, adding event listeners, or performing actions on multiple elements at once.

Related Questions: