return elements that match specified CSS selector(s)

What is the difference between querySelector() and querySelectorAll()?

Answers:

  • querySelector() and querySelectorAll() are both methods available in the Document Object Model (DOM) that allow you to select elements in an HTML document using CSS selectors. However, they have some key differences in terms of functionality and return values:

    querySelector()

    • Returns: The first element that matches the specified CSS selector. If no elements match, it returns null.
    • Usage: Useful when you want to select a single element. For example, selecting an element by its ID or the first occurrence of a specific class or tag.
    • Example:
      let element = document.querySelector('.my-class');
      // This returns the first element with the class "my-class"
      

    querySelectorAll()

    • Returns: A NodeList containing all elements that match the specified CSS selector. If no elements match, it returns an empty NodeList (which is not null).
    • Usage: Useful when you want to select multiple elements that match a specific selector and iterate over them or perform operations on each.
    • Example:
      let elements = document.querySelectorAll('.my-class');
      // This returns a NodeList of all elements with the class "my-class"
      

    Summary of Differences

    1. Return Type: querySelector() returns a single element or null, while querySelectorAll() returns a NodeList (which behaves like an array) containing all matching elements.
    2. Selector Matching: querySelector() stops searching after finding the first match, whereas querySelectorAll() finds all matches in the DOM.

    Example Usage

    <div class="my-class">First</div>
    <div class="my-class">Second</div>
    <div class="my-class">Third</div>
    
    <script>
      let firstElement = document.querySelector('.my-class'); // returns the first <div>
      let allElements = document.querySelectorAll('.my-class'); // returns a NodeList of all <div> elements
      console.log(firstElement.textContent); // Outputs: First
      allElements.forEach(function(el) {
          console.log(el.textContent); // Outputs: First, Second, Third
      });
    </script>
    

    In summary, use querySelector() when you need only the first matching element, and querySelectorAll() when you need to work with multiple elements.

Related Questions: