return elements that match specified CSS selector(s)

Can querySelectorAll() return elements from different levels of the DOM?

Answers:

  • Yes, querySelectorAll() can return elements from different levels of the DOM. It allows you to select multiple elements that match a specified CSS selector, regardless of their position in the DOM tree.

    When you use document.querySelectorAll(selector), it searches through the entire document and collects all elements that match the provided selector, even if they are nested within different parent elements.

    For example, consider the following HTML structure:

    <div class="container">
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
    </div>
    <section>
        <div class="item">Item 3</div>
    </section>
    

    Using the following JavaScript code:

    const items = document.querySelectorAll('.item');
    console.log(items);
    

    This will return a NodeList containing all three .item elements, even though they are not all within the same parent container. The items are indeed from different levels of the DOM but still match the specified selector.

    You can then iterate over the NodeList to manipulate or work with those elements as needed.

Related Questions: