Tutorials Tonight's Logo
Follow Us

JavaScript querySelectorAll With Practical 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 and then take certain action on those elements.

In such cases, there could no better choice than the querySelectorAll method.

querySelectorAll JavaScript

Introduction to querySelectorAll method

querySelectorAll method is used to select elements from the document. It returns a static NodeList (an array-like object) that contains a list of all elements that match the specified selectors or group of selectors.

The selectors here are any valid CSS selectors.

let elements = document.querySelectorAll(selectors);

You can call the querySelectorAll method directly on the document or on any HTML element.

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>.

let elements = document.querySelectorAll("*");
// * is universal selector

Get elements by tag name

Use element CSS selector with the querySelectorAll method to select all the matching elements within the document.

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")

Get 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, so to access the element you have to loop through the list using for loop or forEach loop.

Example

<body>
  <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>
</body>

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

Get 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].

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.

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 querySelectorAll method, it's used and worked with multiple examples and selecting all kind of query with both simple and complex selectors.

More Learning

Want to learn more about programming and web development? We have a few recommendations for you.

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.