return elements that match specified CSS selector(s)

How can I use querySelectorAll() to select elements by class name?

Answers:

  • You can use the querySelectorAll() method in JavaScript to select elements by class name. The querySelectorAll() method takes a CSS selector string as an argument and returns a static NodeList of elements that match the selector.

    To select elements by class name, you'll need to prefix the class with a dot (.). Here's the basic syntax:

    const elements = document.querySelectorAll('.className');
    

    In this code:

    • Replace className with the actual name of the class you want to select.
    • The variable elements will hold a NodeList of all elements in the document that have the specified class.

    Example

    Here’s a simple example that demonstrates how to use querySelectorAll() to select elements by class name:

    <!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="other">Item 4</div>
    
        <script>
            // Select all elements with the class name 'example'
            const elements = document.querySelectorAll('.example');
    
            // Iterate over the NodeList and log the text content of each element
            elements.forEach(element => {
                console.log(element.textContent);
            });
        </script>
    </body>
    </html>
    

    Explanation:

    1. In the example, there are multiple <div> elements with the class name example.
    2. The document.querySelectorAll('.example') selects all elements with that class.
    3. The script then iterates over the NodeList using forEach() to log the text content of each selected element.

    Notes:

    • The NodeList returned by querySelectorAll() is static, meaning it will not automatically update if the DOM changes (e.g., if elements are added or removed after the selection).
    • You can also combine selectors. For example, document.querySelectorAll('div.example') will select only <div> elements with the class example.

Related Questions: