JavaScript document.querySelectorAll()

The JavaScript querySelectorAll() method returns all elements with the specified CSS selector. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>This is para one</p>
   <p class="redPara">This is para two</p>
   <p>This is para three</p>
   <p>This is para four</p>
   <p class="redPara">This is para five</p>
   
   <script>
      var ec = document.querySelectorAll(".redPara");
      for(var i=0; i<ec.length; i++)
         ec[i].style.color = "red";
   </script>
   
</body>
</html>
Output

This is para one

This is para two

This is para three

This is para four

This is para five

See, all elements with the specified class name, that is, redPara, were returned. And I've changed the style of all those elements, one by one, using JavaScript.

In the preceding example, the following JavaScript statement:

var ec = document.querySelectorAll(".redPara");

selects all of the elements in the document that have a class of "redPara". The querySelectorAll() function returns a NodeList of all matching elements. And then the following JavaScript code for the "for" loop:

for(var i=0; i<ec.length; i++)

sets up a loop that will iterate through each of the elements in the "ec" NodeList. Finally, the following statement:

ec[i].style.color = "red";

accesses each element's style property in the "ec" NodeList and sets its color property to "red" The text color of each of the selected "p" elements is changed to red.

JavaScript querySelectorAll() Syntax

The syntax of querySelectorAll() method in JavaScript, is:

document.querySelectorAll(x)

The x refers to a CSS selector. If no match found, null is returned.

Advantages of the querySelectorAll() function in JavaScript

Disadvantages of the querySelectorAll() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!