return elements that match specified CSS selector(s)

How do I use querySelectorAll() for multiple elements?

Answers:

  • The querySelectorAll() method in JavaScript is used to select all elements in the document that match a specified CSS selector. When you want to select multiple elements, you can either use a single selector that combines different selectors or use a comma to separate multiple selectors.

    Here’s how you can use querySelectorAll() for multiple elements:

    Example 1: Using a Combined Selector

    If you want to select elements that share a common class or another attribute, you can use a single combined selector. For example, if you want to select all <div> elements and all <p> elements, you can use a combined selector:

    const elements = document.querySelectorAll('div, p');
    

    Example 2: Using Multiple Selectors

    You can also specify multiple individual selectors separated by commas. For example, if you want to select all elements with the classes .class1, .class2, and all <span> elements, you can do it like this:

    const elements = document.querySelectorAll('.class1, .class2, span');
    

    Example 3: Selecting By Tag and Class

    If you want to select all <h1> elements and all elements with a specific class, you can do it as follows:

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

    Working with the Selected Elements

    The result of querySelectorAll() is a NodeList, which is a collection of nodes based on your query. You can then iterate over this list or work with it in other ways. For example:

    const elements = document.querySelectorAll('div, p');
    
    elements.forEach(element => {
        console.log(element.textContent); // Logs the text content of each selected element
    });
    

    Summary

    • Use a combined selector with , to select multiple elements.
    • Iterate over the resulting NodeList to manipulate or read the elements as needed.

    This method allows for flexible and powerful selections based on CSS selectors.