--- title: Element.querySelectorAll() slug: Web/API/Element/querySelectorAll translation_of: Web/API/Element/querySelectorAll ---
返回一个non-live的NodeList
, 它包含所有元素的非活动节点,该元素来自与其匹配指定的CSS选择器组的元素。(基础元素本身不包括,即使它匹配。)
注意:该API的定义已被移动到 {{domxref("ParentNode")}} 接口。
elementList = baseElement.querySelectorAll(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去遍历它(会遍历出其他无关属性)
想要在它身上使用数组方法,必须先把它转换为真正的数组.
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}} |
document.querySelectorAll
document.querySelector
querySelector