return elements that match specified CSS selector(s)

What browsers support querySelectorAll() and its usage with classes and IDs?

Answers:

  • The querySelectorAll() method is widely supported across all modern web browsers, including:

    • Google Chrome
    • Mozilla Firefox
    • Microsoft Edge
    • Safari
    • Opera
    • Internet Explorer (from version 8 and above)

    Usage with Classes and IDs

    The querySelectorAll() method allows you to select elements from the DOM using CSS selectors, including classes and IDs.

    Selecting by Class

    To select all elements with a specific class, you can use the class selector, which is denoted by a period (.) followed by the class name.

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

    This will return a NodeList of all elements that contain the class my-class.

    Selecting by ID

    To select an element by its ID, use the ID selector, which is denoted by a hash (#) followed by the ID name.

    const element = document.querySelectorAll('#my-id');
    

    This will return a NodeList with the element that has the ID my-id. It's worth noting that an ID should be unique in the document, so this typically will return a list with one element.

    Combining Selectors

    You can also combine selectors when using querySelectorAll(). For example, if you want to select all <div> elements with a specific class:

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

    This selects all <div> elements that have the class my-class.

    Example Usage

    Here’s a complete example that uses querySelectorAll() with both classes and IDs:

    <!DOCTYPE html>
    <html>
    <head>
        <title>querySelectorAll Example</title>
    </head>
    <body>
        <div class="my-class" id="first">First DIV</div>
        <div class="my-class" id="second">Second DIV</div>
        <div class="other-class">Third DIV</div>
    
        <script>
            // Select all elements with the class 'my-class'
            const elements = document.querySelectorAll('.my-class');
            elements.forEach(el => {
                console.log(el.textContent); // Logs 'First DIV' and 'Second DIV'
            });
    
            // Select the element with the ID 'first'
            const firstElement = document.querySelectorAll('#first');
            console.log(firstElement[0].textContent); // Logs 'First DIV'
        </script>
    </body>
    </html>
    

    Conclusion

    The querySelectorAll() method is a powerful and flexible way to select DOM elements using CSS-style selectors, and it is supported by all modern browsers, making it a reliable choice for web development.