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:
Explanation
- Line 7: We create a
divelement with two child elements. - Line 8: We define the first
pelement with the classdemo. - Line 9: We define another
pelement with the same classdemo. - Line 14: We define a button tag. The
onClickbutton is hooked to the functionchange(). - Line 17: We define the
change()function in the script tag. - Line 18: We apply
querySelectorAll()on thedocumentand pass a CSS selector name. Here, it is thedemoclass. It returns all the elements with the same selector.elemis the list of elements with selectordemo. - Line 19: We apply
style.colortoelem[0], which is the first element with thedemoselector.