目录获取文档中id="container"的元素获取第一个p元素获取文档中的第一个class="lover"的元素获取class=&ldquo
html 的DOM querySelector()方法可以不需要额外的Jquery等支持,也可以方便的获取DOM元素,语法跟jQuery类似。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="contatiner">huang</div>
<script type="text/javascript">
var destination = document.querySelector("#contatiner");
console.log(destination);
</script>
</body>
</html>
注意:
querySelector() 方法仅仅返回匹配指定选择器的第一个元素。如果你需要返回所有的元素,请使用 querySelectorAll() 方法替代。
参数类型可以为如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>张露露,我爱你</p>
<p>黄宝康,我也爱你</p>
<script type="text/javascript">
var node = document.querySelector("p");
console.log(node);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span class="lover">张露露</span>
<span class="lover">黄宝康</span>
<script type="text/javascript">
var node = document.querySelector(".lover");
console.log(node);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span class="lover">张露露</span>
<p class="lover">黄宝康</p>
<script type="text/javascript">
var node = document.querySelector("p.lover");
console.log(node);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a href="Http://www.baidu.com">百度一下</a>
<a href="https://www.taobao.com" target="_blank">淘宝一下</a>
<script type="text/javascript">
var node = document.querySelector("a[target]");
console.log(node);
</script>
</body>
</html>
以下代码将为文档的第一个 <h2>
元素添加背景颜色:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h2>二级标题</h2>
<h3>三级标题</h3>
<script type="text/javascript">
document.querySelector("h2,h3").style.backgroundColor = "blue";
</script>
</body>
</html>
但是,如果文档中 <h3>
元素位于 <h2>
元素之前,<h3>
元素将会被设置指定的背景颜色。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>三级标题</h3>
<h2>二级标题</h2>
<script type="text/javascript">
document.querySelector("h2,h3").style.backgroundColor = "blue";
</script>
</body>
</html>
多元素选择时,哪个先匹配就是谁咯,只有一个被选中。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 解读document.querySelector()方法
本文链接: https://www.lsjlt.com/news/197980.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0