What is the querySelectorAll() method in HTML DOM?

Overview

The querySelectorAll() method returns all elements from a DOM tree with the same selector.

The method is called on the parent node document.

Parameter

The parameter for the function is the value of the class property.

Return value

This function returns all the elements with the specified class as an array.

Code

The following code selects all elements with the class value demo and updates the style of the first element only:

  • HTML

Explanation

  • Line 7: We create a div element with two child elements.
  • Line 8: We define the first p element with the class demo.
  • Line 9: We define another p element with the same class demo.
  • Line 14: We define a button tag. The onClick button is hooked to the function change().
  • Line 17: We define the change()function in the script tag.
  • Line 18: We apply querySelectorAll() on the document and pass a CSS selector name. Here, it is the demo class. It returns all the elements with the same selector. elem is the list of elements with selector demo.
  • Line 19: We apply style.color to elem[0], which is the first element with the demo selector.

Free Resources