return elements that match specified CSS selector(s)

What is querySelectorAll() in JavaScript?

Answers:

  • querySelectorAll() is a method in the Document Object Model (DOM) API in JavaScript that allows you to select multiple elements from the document (HTML) based on a specified CSS selector. This method returns a static NodeList containing all the elements that match the provided selector.

    Syntax

    document.querySelectorAll(selectors);
    

    Parameters

    • selectors: A string containing one or more CSS selectors separated by commas. You can use any valid CSS selector to match elements in the document.

    Returns

    • A NodeList of all elements that match the specified selector. A NodeList is similar to an array but is not an actual array. It can be iterated over but does not have array-specific methods like map() or forEach() in all environments.

    Example Usage

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

    1. Select all paragraphs:

      const paragraphs = document.querySelectorAll('p');
      paragraphs.forEach(paragraph => {
          console.log(paragraph.textContent);
      });
      
    2. Select all elements with a specific class:

      const items = document.querySelectorAll('.item');
      items.forEach(item => {
          // Do something with each item
      });
      
    3. Select multiple types of elements:

      const headersAndSections = document.querySelectorAll('h1, h2, section');
      headersAndSections.forEach(el => {
          // Process headers and sections
      });
      
    4. Using ID and attributes:

      const specialItems = document.querySelectorAll('#special, [data-role="admin"]');
      specialItems.forEach(item => {
          // Handle special items
      });
      

    Important Notes

    • querySelectorAll() returns a static NodeList; that means it does not automatically update if the document changes.
    • If no elements match the selectors, it returns an empty NodeList.
    • The order of elements in the NodeList corresponds to the order they appear in the HTML document.

    querySelectorAll() is widely used for selecting multiple elements efficiently based on various criteria, leveraging the power of CSS selectors for targeting elements in the DOM.

Related Questions: