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

How to use querySelector method

不言
Release: 2019-02-14 15:23:15
Original
20764 people have browsed it

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)
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template