JavaScript querySelectorAll with Examples


In this tutorial, you will learn about javascript querySelectorAll, how this method can help to select any element or a group of elements from the DOM with examples.

As a web developer, you may come across many situations when you need to select a group of elements from DOM that shares similar properties like the same element or same class.

In such cases, there could no better choice than the querySelectorAll method. It can select a whole lot of elements from the DOM having some similar properties.

querySelectorAll JavaScript

Following is the list of things we are going to see in this tutorial.

    Table Of Contents

  1. Introduction to JavaScript querySelectorAll
  2. Universal selector
  3. Select elements by tag name
  4. Select elements by class
  5. Select elements by a list of matches
  6. Select elements by attribute
  7. Select elements by combining selectors
  8. Special cases

Introduction To JavaScript querySelectorAll method

The JavaScript querySelectorAll method is used to select elements in the document using CSS selectors and returns all the matching elements as a list.

The method returns a static NodeList (an array-like object) that contains a list of all elements that match the specified selectors or group of selectors.

Syntax:

document.querySelectorAll(selectors);
// or
parent.querySelectorAll(selectors);

The selectors parameter is a string that specifies the selectors to match.

You can call the querySelectorAll method directly on the document or on any other HTML element (parent).

  1. The method applied on the document - When applied on a document it will select all elements within the document that matches the query.

    Example - Method applied on the document

    <body>
      <div class="container">
        <p>Paragraph in container 1</p>
        <p>Paragraph in container 2</p>
        <p>Paragraph in container 3</p>
        <p>Paragraph in container 4</p>
      </div>
      <p>Outer paragraph 1</p>
      <p>Outer paragraph 2</p>
      <p>Outer paragraph 3</p>
      <p>Outer paragraph 4</p>
    
      <script>
        // selecting all paragraph in document
        let elements = document.querySelectorAll("p");
        console.log(elements);
      </script>
    </body>

    Output:
    The method returns all 8 paragraphs from the document.

    output 1
  2. The method applied on any element - When applied on any HTML element then it will return all the children elements of the specified HTML element that matched the query.

    Example - Method applied on any HTML element

    <body>
      <div class="container">
        <p>Paragraph in container 1</p>
        <p>Paragraph in container 2</p>
        <p>Paragraph in container 3</p>
        <p>Paragraph in container 4</p>
      </div>
      <p>Outer paragraph 1</p>
      <p>Outer paragraph 2</p>
      <p>Outer paragraph 3</p>
      <p>Outer paragraph 4</p>
    
      <script>
        let parentElement = document.querySelector(".container");
        // selecting all paragraph of container only
        let elements = parentElement.querySelectorAll("p");
        console.log(elements);
      </script>
    </body>

    Output:
    The method return paragraph element only from the parent element which is 4 in number.

    output 2

Note: If the specified selector is a CSS pseudo-element then the method returns an empty list.


A universal selector to select all elements

The universal selector (*) selects all the elements of the document including <meta>, <title>, <style>, <script> and other elements of <body>.

Example - Universal selector

// Select all the elements in the document
var all = document.querySelectorAll('*');
console.log(all);

Select elements by tag name

To select elements by tag name, you can pass the tag name as a parameter to the querySelectorAll method. If you apply the method on the document, then it will select all the elements of the specified tag name within the document and if you apply it on any element then it will select all the elements of the specified tag name within the specified element.

Look at the following. Select all the Nodelist of <p> elements in the DOM:

let paragraphs = document.querySelectorAll("p")

To select all the Nodelist of <img> elements (images) in the DOM:

let images = document.querySelectorAll("img")

Select All Elements By Class

To select all elements of a class pass the class name preceding with a dot(.) as an argument in the querySelectorAll method. It will return all elements of the specified class within the document or in the parent element.

Since the method returns an array-like object which is a list of all matched elements, to access the element you have to loop through the list using for loop or forEach loop.

Example

<p class="box">Paragraph 1 with box class.</p>
<p class="box">Paragraph 2 with box class.</p>
<p class="box">Paragraph 3 with box class.</p>
<p class="box">Paragraph 4 with box class.</p>
<p class="box">Paragraph 5 with box class.</p>
<button onclick="selectElements()">Select elements</button>

<script>
  function selectElements() {
    let elements = document.querySelectorAll(".box");
    // using forEach loop
    elements.forEach(element => {
      element.style.background = "lightgreen";
    });
    // using for loop
    for (let i = 0; i < elements.length; i++) {
      elements[i].style.color = "brown";
    }
  }
</script>

Output:
Used both for loop and forEach loop to access the elements of the list.

output 3

Getting a list of matches

The querySelectorAll method returns all the matches of the list of matching elements.

The example below returns all the elements within the document having class either of box or container.

Example

let elements = document.querySelectorAll(".box, .container");
// loop through all the elements
elements.forEach(element => {
  element.style.background = "lightgreen";
});

Output:
The method returns all the elements having either of 2 classes as a Nodelist.

output 4

Select elements by attribute

To select an element by the attribute pass the attribute name in the method by wrapping it in a square bracket. Example [title].

Example

let elements = document.querySelectorAll("[title]");
// loop through all the elements
elements.forEach(element => {
  element.style.background = "lightgreen";
});

Let's now select all the paragraph that has a title attribute. In the following example select all the paragraph elements with the attribute [title] with any value.

let elements = document.querySelectorAll("p[title]");

Getting all elements with the same attribute value

Pass the attribute with its value as a selector in the method. Like to select all anchor elements whose href value is https://www.tutorialstonight.com, the code would be as follows:

let elements = document.querySelectorAll("a[href='https://www.tutorialstonight.com']")

Combining selectors to select a group of elements

Suppose there is a container having multiple lists of items and you have to select 1st list element of all the lists using javascript. You can achieve it by the querySelectorAll method.

Let the HTML code of the lists be as follows and the first element of all the lists is to be selected.

<div class="container">
  <ul>
    <li>List number 1. Item Number 01.</li>
    <li>List number 1. Item Number 02.</li>
    <li>List number 1. Item Number 03.</li>
    <li>List number 1. Item Number 04.</li>
    <li>List number 1. Item Number 05.</li>
  </ul>
  <ul>
    <li>List number 2. Item Number 01.</li>
    <li>List number 2. Item Number 02.</li>
    <li>List number 2. Item Number 03.</li>
    <li>List number 2. Item Number 04.</li>
    <li>List number 2. Item Number 05.</li>
  </ul>
  <ul>
    <li>List number 3. Item Number 01.</li>
    <li>List number 3. Item Number 02.</li>
    <li>List number 3. Item Number 03.</li>
    <li>List number 3. Item Number 04.</li>
    <li>List number 3. Item Number 05.</li>
  </ul>
</div>

Use combinator selectors to grab the desired elements.

Example

let elements = document.querySelectorAll(".container ul li:nth-child(1)");
// loop through all the elements
elements.forEach(element => {
  element.style.background = "lightgreen";
});

Output:

output 5

Special Case

The querySelectorAll method behaves differently than other JavaScript DOM libraries.

Conside the example below:

<body>
  <div class="outer">
    <div class="middle">
      <div class="inner">inner</div>
    </div>
  </div>
  <button onclick="selectElements()">Select elements</button>

  <script>
    function selectElements() {
      let middle = document.querySelector(".middle");
      let elements = middle.querySelectorAll(".outer .inner");
      console.log(elements); // return 1 element not 0
    }
  </script>
</body>

When you select inner class on .middle element with query of ".outer .inner" then it returns .inner element even though .outer is not a descendant (child) of .middle class element.

By default, the querySelectorAll method only varifies the last element in the selector within the search scope.

To restore the expected behavior use :scope pseudo-class with it.

let middle = document.querySelector(".middle");
let elements = middle.querySelectorAll(":scope .outer .inner");
console.log(elements); // return blank nodelist

Conclusion

In this section, we learned about the JavaScript querySelectorAll method, it's used and worked with multiple examples and selecting all kinds of queries with both simple and complex selectors.