What is the querySelector() method in Dom?
Overview
In this shot, we will learn to get the element object using the querySelector() method. This method is applied to the parent element and returns the first child that matches the specified selector, which was passed in the method.
The querySelector() method can be applied on any parent node in the document and passed with a parameter, which is the value that is assigned to a selector. For example, the class has the value test and then passes .test in it. This method returns only the first child that matches with the selector.
There is a slight difference between the querySelectorAll() and the querySelector() methods. The querySelectorAll() method returns the list with all elements that have the specified selector, whereas the querySelector() method only returns the first element that has the specified selector.
Code
We will write a code to find an element with a specified selector, and then we will style the element with the same selector.
Explanation
-
In line 7, we can see a
divelement with the IDelemand two child elements. -
In line 8, we define the first
pelement with thedemoclass. -
In line 9, we define another
pelement with the samedemoclass. -
In line 14, we write a button tag with a
change()function. This function is called when the user clicks its button tag. -
In line 17, we define the
change()function in the script tag. -
In line 18, we get the parent
divelement, usinggetElementById(), and pass thedivID in it. -
In line 19, we apply the
querySelector()method on thedivelement and pass the selector in it. This returns the first child with the classdemoselector. We also applystyle.colorto change the color of the text.
Output
When we click the button, the text color of the first p element with the CSS class demo is changed, and the other element with the same CSS class remains unchanged.