--- title: Element.querySelectorAll() slug: Web/API/Element/querySelectorAll translation_of: Web/API/Element/querySelectorAll ---
{{APIRef("DOM")}}

返回一个non-live的NodeList, 它包含所有元素的非活动节点,该元素来自与其匹配指定的CSS选择器组的元素。(基础元素本身不包括,即使它匹配。)

注意:该API的定义已被移动到 {{domxref("ParentNode")}} 接口。

语法

elementList = baseElement.querySelectorAll(selectors);

其中

示例

dataset selector & attribute selectors

<section class="box" id="sect1">
  <div class="funnel-chart-percent1">10.900%</div>
  <div class="funnel-chart-percent2">3700.00%</div>
  <div class="funnel-chart-percent3">0.00%</div>
</section>
// dataset selectors
const refs = [...document.querySelectorAll(`[data-name*="funnel-chart-percent"]`)];

// attribute selectors
// const refs = [...document.querySelectorAll(`[class*="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class^="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class$="funnel-chart-percent"]`)];
// const refs = [...document.querySelectorAll(`[class~="funnel-chart-percent"]`)];

下面的例子返回了HTML文档中的body元素的所有p后代元素:

var matches = document.body.querySelectorAll('p');

下面的例子返回了id'test'的元素的所有class属性为'highlighted'的所有div后代元素的p子元素:

var el = document.querySelector('#test');
var matches = el.querySelectorAll('div.highlighted > p');

下面的例子返回了el元素的后代元素中所有拥有data-src属性的iframe元素:

var matches = el.querySelectorAll('iframe[data-src]');

附注

如果指定的CSS选择器不合法,则会抛出一个SYNTAX_ERR 异常.

返回值是一个NodeList对象,所以不推荐使用 for...in去遍历它(会遍历出其他无关属性)

想要在它身上使用数组方法,必须先把它转换为真正的数组.

浏览器兼容性

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1 {{CompatGeckoDesktop("1.9.1")}} 8 10 3.2 (525.3)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatGeckoMobile("1.9.1")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatVersionUnknown}}

规范

相关链接