return elements that match specified CSS selector(s)

How do you use querySelectorAll() in JavaScript?

Answers:

  • The querySelectorAll() method in JavaScript is a powerful function that allows you to select multiple elements from the DOM (Document Object Model) based on CSS selectors. It returns a static NodeList containing all elements that match the specified selectors.

    Here’s how to use querySelectorAll():

    Syntax

    document.querySelectorAll(selectors);
    
    • selectors: A string containing one or more CSS selectors separated by commas.

    Example Usage

    Here are a few examples illustrating how to use querySelectorAll():

    1. Selecting Multiple Elements

    Suppose you have a simple HTML structure:

    <ul>
        <li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
    </ul>
    

    You can select all list items with the class "item":

    const items = document.querySelectorAll('.item');
    
    items.forEach((item) => {
        console.log(item.textContent);  // Outputs: "Item 1", "Item 2", "Item 3"
    });
    

    2. Selecting Elements by Tag

    You can also select elements by their tag name:

    const listItems = document.querySelectorAll('li');
    
    listItems.forEach((li) => {
        console.log(li.textContent);  // Outputs: "Item 1", "Item 2", "Item 3"
    });
    

    3. Using Multiple Selectors

    You can combine multiple selectors:

    const items = document.querySelectorAll('.item, .other-class');
    
    items.forEach((item) => {
        console.log(item.textContent);
    });
    

    4. Selecting Nested Elements

    You can also select elements nested within other elements. For instance:

    <div class="container">
        <p class="text">Text 1</p>
        <p class="text">Text 2</p>
    </div>
    

    You can select the paragraphs within the container:

    const paragraphs = document.querySelectorAll('.container .text');
    
    paragraphs.forEach((p) => {
        console.log(p.textContent);  // Outputs: "Text 1", "Text 2"
    });
    

    Important Notes

    • querySelectorAll() returns a static NodeList. This means that it does not update when the DOM changes. If you want a live collection, you should use getElementsByClassName, getElementsByTagName, or getElementsByName.
    • You can use any valid CSS selector syntax, including class selectors, ID selectors, attribute selectors, pseudo-classes, and more.

    That’s the basic usage of querySelectorAll(). It is a versatile method that can be very helpful for DOM manipulation in JavaScript!

Related Questions: