Home > Article > Web Front-end > How to use querySelector method
querySelector() method can be used to return an element in the document that matches the specified CSS selector. If you need to return all elements, you need to use the querySelectorAll() method instead. Let's take a look at the specific usage of the querySelector method. .
Let’s first take a look at the basic syntax of querySelector()
document.querySelector(CSS selectors)
CSS selectors represent the CSS of one or more matching elements Selector. Elements can be selected using their id, class, type, attributes, attribute values, etc.
Note: For multiple selectors, use commas to separate them.
Let’s look at a specific example
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <h2 class="example">文本的标题</h2> <p class="example"> 文本的段落。</p> <button onclick="myFunction()">按钮</button> <script> function myFunction() { document.querySelector(".example").style.backgroundColor = "red"; } </script> </body> </html>
The effect is as follows: When the "button" is clicked, the background color of the text title will become as follows Red
This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to use querySelector method. For more information, please follow other related articles on the PHP Chinese website!