HTML Document querySelectorAll() Method: Getting All Matching Elements

The querySelectorAll() method in the HTML Document interface is a powerful tool for selecting all elements within a document that match a specified CSS selector. Unlike querySelector(), which returns only the first matching element, querySelectorAll() returns a NodeList containing all matching elements in the order they appear in the document. This method is essential for manipulating multiple elements at once, applying styles, or extracting data from a set of elements.

What is the querySelectorAll() Method?

The querySelectorAll() method allows you to select all elements in an HTML document that match a specified CSS selector. It returns a static NodeList representing the collection of elements.

Purpose of the querySelectorAll() Method

The primary purpose of the querySelectorAll() method is to:

  • Select all elements that match a specific CSS selector.
  • Return a NodeList containing all matching elements.
  • Enable batch manipulation of multiple elements at once.
  • Facilitate dynamic updates and modifications of the DOM.

Syntax of querySelectorAll()

The syntax for the querySelectorAll() method is straightforward:

const nodeList = document.querySelectorAll(selectors);

Parameters

Parameter Type Description
`selectors` String A string containing one or more CSS selectors to match elements against. This can include any valid CSS selector, such as class names, IDs, tag names, attribute selectors, and pseudo-classes.

Return Value

  • NodeList: A static NodeList containing all elements that match the specified selectors, in the order they appear in the document. If no elements match, an empty NodeList is returned.

Examples of querySelectorAll()

Let’s explore some examples demonstrating the use of the querySelectorAll() method.

Selecting Elements by Tag Name

This example selects all <p> (paragraph) elements in the document.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() by Tag Name</title>
  </head>
  <body>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <div>This is a div element.</div>
    <p>This is the third paragraph.</p>

    <script>
      const paragraphsTagName = document.querySelectorAll("p");
      paragraphsTagName.forEach((p, index) => {
        p.style.color = "blue";
        p.textContent = `Paragraph ${index + 1}`;
      });
    </script>
  </body>
</html>

Output:
All paragraph elements’ text color will change to blue, and their content will be updated to “Paragraph 1”, “Paragraph 2”, and “Paragraph 3”.

Selecting Elements by Class Name

This example selects all elements with the class name “highlight”.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() by Class Name</title>
  </head>
  <body>
    <div class="highlight">First highlighted element.</div>
    <div>Normal element.</div>
    <div class="highlight">Second highlighted element.</div>

    <script>
      const highlightedElementsClass = document.querySelectorAll(".highlight");
      highlightedElementsClass.forEach((element) => {
        element.style.backgroundColor = "yellow";
      });
    </script>
  </body>
</html>

Output:
The background color of elements with the class “highlight” will change to yellow.

Selecting Elements by ID

Although IDs are unique, querySelectorAll() can still be used to select an element by its ID.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() by ID</title>
  </head>
  <body>
    <div id="uniqueElement">This is a unique element.</div>
    <div>Another element.</div>

    <script>
      const uniqueElementId = document.querySelectorAll("#uniqueElement");
      uniqueElementId.forEach((element) => {
        element.style.border = "2px solid red";
      });
    </script>
  </body>
</html>

Output:
The element with the ID “uniqueElement” will have a red border.

Selecting Elements by Attribute

This example selects all <a> (anchor) elements with the target="_blank" attribute.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() by Attribute</title>
  </head>
  <body>
    <a href="https://www.example.com" target="_blank">Example Link 1</a>
    <a href="https://www.example.com">Example Link 2</a>
    <a href="https://www.example.com" target="_blank">Example Link 3</a>

    <script>
      const externalLinksAttribute = document.querySelectorAll(
        'a[target="_blank"]'
      );
      externalLinksAttribute.forEach((link) => {
        link.style.fontWeight = "bold";
      });
    </script>
  </body>
</html>

Output:
The font weight of anchor elements with the attribute target="_blank" will be bold.

Selecting Elements Using Multiple Selectors

This example demonstrates using multiple selectors to select elements that match any of the specified criteria.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() with Multiple Selectors</title>
  </head>
  <body>
    <p class="highlight">First highlighted paragraph.</p>
    <div>Normal div.</div>
    <div id="uniqueElement">Unique element.</div>

    <script>
      const multipleSelectors = document.querySelectorAll(".highlight, #uniqueElement");
      multipleSelectors.forEach((element) => {
        element.style.fontSize = "20px";
      });
    </script>
  </body>
</html>

Output:
The font size of elements with class “highlight” and the element with ID “uniqueElement” will be 20px.

Selecting Elements within a Specific Container

This example selects all <li> (list item) elements within a specific <ul> (unordered list) element.

<!DOCTYPE html>
<html>
  <head>
    <title>querySelectorAll() within a Container</title>
  </head>
  <body>
    <ul id="myList">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
    <ul>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>

    <script>
      const myListItemsContainer = document.getElementById("myList").querySelectorAll("li");
      myListItemsContainer.forEach((item) => {
        item.style.listStyleType = "square";
      });
    </script>
  </body>
</html>

Output:
The list style type of list items within the <ul> element with ID “myList” will be square.

Real-World Applications of querySelectorAll()

The querySelectorAll() method is used in various real-world applications, including:

  • Form Validation: Selecting all invalid form fields and highlighting them.
  • Dynamic Content Updates: Updating multiple elements based on user interactions or data changes.
  • Theming and Styling: Applying different themes or styles to multiple elements simultaneously.
  • Data Extraction: Extracting data from multiple elements, such as table rows or list items.

Important Considerations

  • Static NodeList: The NodeList returned by querySelectorAll() is static, meaning it does not update automatically if the DOM changes after the selection.
  • Performance: Using complex or inefficient selectors can impact performance, especially in large documents.
  • Browser Compatibility: The querySelectorAll() method is widely supported across modern browsers.

Conclusion

The querySelectorAll() method is a powerful and versatile tool for selecting multiple elements in an HTML document. By understanding its syntax, usage, and real-world applications, you can effectively manipulate and update the DOM to create dynamic and interactive web pages. Whether you’re updating styles, extracting data, or validating forms, querySelectorAll() provides a robust solution for selecting and manipulating multiple elements at once.