return elements that match specified CSS selector(s)

Can querySelectorAll() be used on elements other than the document?

Answers:

  • Yes, the querySelectorAll() method can be used on any element that is a Node in the DOM, not just on the document. This means that you can call querySelectorAll() on any HTML element to search for its descendants that match a specific CSS selector.

    Here’s a simple example to illustrate this:

    <div id="parent">
        <p class="child">Child 1</p>
        <p class="child">Child 2</p>
        <span class="child">Child 3</span>
    </div>
    
    <script>
        // Selecting the parent element
        const parent = document.getElementById('parent');
        
        // Using querySelectorAll on the parent element
        const children = parent.querySelectorAll('.child');
        
        // Logging the children elements
        children.forEach(child => {
            console.log(child.textContent); // Outputs: "Child 1", "Child 2", "Child 3"
        });
    </script>
    

    In this example, we call querySelectorAll() on the parent div element, and it successfully selects all child elements with the class child. This demonstrates that querySelectorAll() can indeed be used with any element, not just the document.

Related Questions: