Home >Web Front-end >JS Tutorial >How to use querySelector method

How to use querySelector method

不言
不言Original
2019-02-14 15:23:1520730browse

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. .

How to use 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

How to use querySelector method

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn