querySelectorAll() the best JavaScript function in the world!

Can querySelectorAll() select elements within a specific parent or ancestor element?

1 answer

  1. Yes, `querySelectorAll()` can select elements within a specific parent or ancestor element. To do this, you need to call `querySelectorAll()` on the parent or ancestor element, rather than calling it on the document.

    Here's an example:

    ```html
    <div id="parent">
    <div class="child">Child 1</div>
    <div class="child">Child 2</div>
    </div>

    <div id="another-parent">
    <div class="child">Child 3</div>
    <div class="child">Child 4</div>
    </div>
    ```

    ```javascript
    // Select the parent element
    const parentElement = document.querySelector("#parent");

    // Select all child elements with the class "child" within the parent element
    const childElements = parentElement.querySelectorAll(".child");

    console.log(childElements); // NodeList [Child 1, Child 2]
    ```

    In this example, we first selected the parent element with the `querySelector()` method. Then, we called `querySelectorAll()` on the parent element to select all child elements with the class "child". This returned a NodeList containing only the child elements within the specific parent.

Related Questions