return elements that match specified CSS selector(s)

How do I select multiple elements using querySelectorAll()?

Answers:

  • The querySelectorAll() method in JavaScript is used to select multiple elements from the DOM based on a specified CSS selector. The method returns a NodeList of all elements that match the specified selector.

    Syntax

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

    Steps to use querySelectorAll()

    1. Define Your Selector: Create your CSS selector string. This can be any valid CSS selector, including class selectors, ID selectors, attribute selectors, and more.

    2. Call the Method: Pass the selector as an argument to querySelectorAll(), which is called on the document object or a specific element.

    3. Use the Result: The result is a NodeList, which can be iterated over using methods like forEach, or can be converted to an array if you need to use array methods.

    Examples

    1. Selecting all paragraphs:

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

      const items = document.querySelectorAll('.item');
      items.forEach(item => {
          item.style.color = 'blue';
      });
      
    3. Selecting by multiple classes:

      const specialItems = document.querySelectorAll('.item.special');
      specialItems.forEach(item => {
          item.classList.add('highlight');
      });
      
    4. Selecting elements using IDs (note the use of # for IDs):

      const element = document.querySelectorAll('#myId');
      console.log(element); // Returns a NodeList, typically contains one element
      
    5. Using attribute selectors:

      const inputs = document.querySelectorAll('input[type="text"]');
      inputs.forEach(input => {
          input.value = 'Hello';
      });
      

    Note

    • The NodeList returned by querySelectorAll() is not an array, but you can convert it to an array if needed:

      const nodesArray = Array.from(document.querySelectorAll('div'));
      // or
      const nodesArray = [...document.querySelectorAll('div')];
      
    • Remember that querySelectorAll() returns elements that match the selector at the time the method is called. If the DOM changes later (e.g., elements are added or removed), the NodeList will not be updated.

    Using querySelectorAll() is a powerful way to work with multiple elements in the DOM efficiently.

Related Questions: