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.
We will write a code to find an element with a specified selector, and then we will style the element with the same selector.
In line 7, we can see a div
element with the ID elem
and two child elements.
In line 8, we define the first p
element with the demo
class.
In line 9, we define another p
element with the same demo
class.
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 div
element, using getElementById()
, and pass the div
ID in it.
In line 19, we apply the querySelector()
method on the div
element and pass the selector in it. This returns the first child with the class demo
selector. We also apply style.color
to change the color of the text.
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.