HTML DOM Document querySelectorAll() 方法

定义和用法

querySelectorAll() 方法返回与 CSS 选择器匹配的所有元素。

querySelectorAll() 方法返回的是 NodeList。

如果选择器无效,则 querySelectorAll() 方法会抛出 SYNTAX_ERR 异常。

实例

例子 1

选择所有带有 class="example" 的元素:

document.querySelectorAll(".example");

亲自试一试

例子 2

为第一个 <p> 元素添加背景颜色:

const nodeList= document.querySelectorAll("p");
nodeList[0].style.backgroundColor = "red";

亲自试一试

例子 3

为第一个 class="example" 的 <p> 元素添加背景颜色:

const nodeList = document.querySelectorAll("p.example");
nodeList[0].style.backgroundColor = "red";

亲自试一试

例子 4

class="example" 的元素的数量:

let numb = document.querySelectorAll(".example").length;

亲自试一试

例子 5

设置所有 class="example" 的元素的背景颜色:

const nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.backgroundColor = "red";
}

亲自试一试

例子 6

设置所有 <p> 元素的背景颜色:

let nodeList = document.querySelectorAll("p");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.backgroundColor = "red";
}

亲自试一试

例子 7

设置所有使用 "target" 属性的 <a> 元素的边框:

const nodeList = document.querySelectorAll("a[target]");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.border = "10px solid red";
}

亲自试一试

例子 8

设置父元素是 <div> 元素的每个 <p> 元素的背景颜色:

const nodeList = document.querySelectorAll("div > p");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.backgroundColor = "red";
}

亲自试一试

例子 9

设置所有 <h3>、<div> 和 <span> 元素的背景颜色:

const nodeList = document.querySelectorAll("h3, div, span");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.backgroundColor = "red";
}

亲自试一试

语法

document.querySelectorAll(CSSselectors)

参数

参数描述
CSSselectors

必需。一个或多个 CSS 选择器。

CSS 选择器根据 id、类、类型、属性、属性值等选择 HTML 元素。

如需完整列表,请访问我们的 CSS 选择器参考手册

对于多个选择器,请用逗号分隔每个选择器(请参阅上方的实例)。

返回值

类型描述
对象

含有与 CSS 选择器匹配的元素的 NodeList 对象。

如果没有找到匹配项,则返回空的 NodeList 对象。

HTMLCollection 和 NodeList 的区别

NodeListHTMLcollection 非常相似。

两者都是从文档中提取的节点(元素)的类似数组的集合(列表)。可以通过索引号(下标)访问节点。索引从 0 开始。

两者都有 length 属性,它返回列表(集合)中元素的数量。

HTMLCollection 是文档元素的集合。

NodeList 是文档节点(元素节点、属性节点和文本节点)的集合。

HTMLCollection 项目可以通过它们的名称、id 或索引号来访问。

NodeList 项目只能通过它们的索引号访问。

HTMLCollection 始终是实时的集合。

例如:如果将 <li> 元素添加到 DOM 中的列表,则 HTMLCollection 中的列表也会发生变化。

NodeList 通常是静态的集合。

例如:如果将 <li> 元素添加到 DOM 中的列表,则 NodeList 中的列表不会改变。

getElementsByClassName()getElementsByTagName() 方法都返回实时 HTMLCollection。

querySelectorAll() 方法返回静态 NodeList。

childNodes 属性返回实时 NodeList。

浏览器支持

document.querySelectorAll() 是 DOM Level 3 (2004) 特性。

所有浏览器都支持它:

ChromeIEEdgeFirefoxSafariOpera
ChromeIEEdgeFirefoxSafariOpera
支持9-11支持支持支持支持

相关页面

教程:

CSS 选择器

CSS 选择器参考手册

JavaScript Node List 教程

QuerySelector 方法:

Element querySelector() 方法

Element querySelectorAll() 方法

Document querySelector() 方法

Document querySelectorAll() 方法

GetElement 方法:

Document getElementById() 方法

Document getElementsByTagName() 方法

Document getElementsByClassName() 方法