HTML DOM Document querySelectorAll()
描述
querySelectorAll()
方法返回所有匹配 CSS 选择器的元素。
querySelectorAll()
方法返回一个 NodeList。
如果选择器无效,querySelectorAll()
方法会抛出 SYNTAX_ERR 异常
NodeList(节点列表)
NodeList 是一个类似数组的节点集合(列表)。
列表中的节点可以通过索引访问。索引从 0 开始。
length 属性 返回列表中节点的数量。
语法
document.querySelectorAll(CSS 选择器)
参数
参数 | 描述 |
CSS 选择器 | 必需。 一个或多个 CSS 选择器。 CSS 选择器根据 ID、类、类型、属性、属性值等选择 HTML 元素。 有关完整列表,请参阅我们的 CSS 选择器参考。 对于多个选择器,请用逗号分隔每个选择器(参见“更多示例”)。 |
返回值
类型 | 描述 |
对象 | 一个 NodeList 对象,其中包含与 CSS 选择器匹配的元素。 如果没有找到匹配项,则返回一个空的 NodeList 对象。 |
更多示例
为第一个 <p> 元素添加背景颜色
const nodeList= document.querySelectorAll("p");
nodeList[0].style.backgroundColor = "red";
自己动手试一试 »
为第一个 class="example" 的 <p> 元素添加背景颜色
const nodeList = document.querySelectorAll("p.example");
nodeList[0].style.backgroundColor = "red";
自己动手试一试 »
设置所有 class="example" 的元素的背景颜色
const nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己动手试一试 »
设置所有 <p> 元素的背景颜色
let nodeList = document.querySelectorAll("p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己动手试一试 »
设置所有带有 "target" 属性的 <a> 元素的边框
const nodeList = document.querySelectorAll("a[target]");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.border = "10px solid red";
}
自己动手试一试 »
设置父元素是 <div> 元素的每个 <p> 元素的背景颜色
const nodeList = document.querySelectorAll("div > p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己动手试一试 »
设置所有 <h3> 和 <span> 元素的背景颜色
const nodeList = document.querySelectorAll("h3, span");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己动手试一试 »
浏览器支持
document.querySelectorAll()
是 DOM Level 3 (2004) 特性。
所有现代浏览器都完全支持它
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 11 |