return elements that match specified CSS selector(s)

How do you use querySelectorAll() to select multiple elements?

Answers:

  • The querySelectorAll() method is a powerful way to select multiple elements in the DOM (Document Object Model) using CSS selectors. This method returns a static NodeList of all elements that match the specified CSS selector(s). Here's how you can use it:

    Basic Syntax

    const elements = document.querySelectorAll('selector');
    

    Example Usage

    1. Select All Elements of a Specific Type: To select all <div> elements on a page:

      const divElements = document.querySelectorAll('div');
      
    2. Select Elements by Class Name: To select all elements with a specific class (e.g., .my-class):

      const elementsWithClass = document.querySelectorAll('.my-class');
      
    3. Select Elements by ID: The ID selector # can only match one element; however, you can still use it. For example:

      const specificElement = document.querySelectorAll('#my-id');
      
    4. Combine Selectors: You can also combine selectors to get more specific matches. For example, to select all <p> elements with a specific class:

      const paragraphsWithClass = document.querySelectorAll('p.my-class');
      
    5. Attribute Selectors: You can select elements with specific attributes. For example, to select all <input> elements with the attribute type="text":

      const textInputs = document.querySelectorAll('input[type="text"]');
      
    6. Nth-child or nth-of-type Selectors: To select every second <li> in a list:

      const everySecondItem = document.querySelectorAll('li:nth-child(2n)');
      

    Working with the Selected Nodes

    The NodeList returned by querySelectorAll() can be looped over or converted into an array if you need to manipulate the elements further. For example:

    const elements = document.querySelectorAll('.my-class');
    
    elements.forEach(element => {
        // Do something with each element
        console.log(element.textContent);
    });
    

    Or if you need to convert it into an array:

    const elementsArray = Array.from(elements);
    

    Summary

    • Use document.querySelectorAll('selector') to select elements matching the CSS selector.
    • The method returns a static NodeList of matching elements.
    • You can utilize various CSS selectors (tags, classes, IDs, attributes, etc.) to refine your search.
    • Use methods like forEach for easy iteration over the selected elements.

    This is a great way to dynamically interact with multiple elements on your web page using JavaScript.

Related Questions: