定义:
querySelector() 方法返回文档中匹配指定 CSS 选择器的一个元素。
注意: querySelector() 方法仅仅返回匹配指定选择器的第一个元素。如果你需要返回所有的元素,请使用 querySelectorAll() 方法替代。
语法
document.querySelector(CSS selectors)
例子:
1.获取文档中 id="demo" 的元素:
document.querySelector("#demo");
2.获取文档中第一个 <p> 元素:
document.querySelector("p");
3.获取文档中 class="example" 的第一个元素:
document.querySelector(".example");
4.获取文档中 class="example" 的第一个 <p> 元素:
document.querySelector("p.example");
5.获取文档中有 "target" 属性的第一个 <a> 元素:
document.querySelector("a[target]”);
多选择器时:
假定你选择了两个选择器: <h2> 和 <h3> 元素。
以下代码将为文档的第一个 <h2> 元素添加背景颜色:
<h2>A h2 element</h2>
<h3>A h3 element</h3>
document.querySelector("h2, h3").style.backgroundColor = "yellow";
但是,如果文档中 <h3> 元素位于 <h2> 元素之前,<h3> 元素将会被设置指定的背景颜色。
<h3>A h3 element</h3>
<h2>A h2 element</h2>
document.querySelector("h2, h3").style.backgroundColor = "yellow”;
也可以将所有类或者ID或元素都查找出来,然后再将某一项进行修改
document.querySelectorAll(“.xubox_imgsee")[0].style.display="block”;
理解 :
document.querySelectorAll(“.xubox_imgsee”)——>选择所有的select类
[0] ——>指定这一组标签里的第几个(从0开始)
.style.display=“block”——>修改样式为block,原来是display:none

网友评论