Document
方法
querySelectorAll()
returns a static (not live)
NodeList
representing a list of the document's elements that match the specified group of selectors.
注意:
This method is implemented based on the
ParentNode
mixin's
querySelectorAll()
方法。
elementList = parentNode.querySelectorAll(selectors);
selectors
DOMString
containing one or more selectors to match against. This string must be a valid
CSS selector
string; if it's not, a
SyntaxError
exception is thrown. See
使用选择器定位 DOM 元素
for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas.
注意: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See 转义特殊字符 了解更多信息。
A non-live
NodeList
containing one
元素
object for each element that matches at least one of the specified selectors or an empty
NodeList
in case of no matches.
注意:
若指定
selectors
include a
CSS pseudo-element
, the returned list is always empty.
SyntaxError
selectors
string is not valid.
To obtain a
NodeList
of all of the
<p>
elements in the document:
var matches = document.querySelectorAll("p");
This example returns a list of all
<div>
elements within the document with a class of either
note
or
alert
:
var matches = document.querySelectorAll("div.note, div.alert");
Here, we get a list of
<p>
elements whose immediate parent element is a
<div>
with the class
highlighted
and which are located inside a container whose ID is
test
.
var container = document.querySelector("#test");
var matches = container.querySelectorAll("div.highlighted > p");
This example uses an
attribute selector
to return a list of the
<iframe>
elements in the document that contain an attribute named
data-src
:
var matches = document.querySelectorAll("iframe[data-src]");
Here, an attribute selector is used to return a list of the list items contained within a list whose ID is
userlist
which have a
data-active
attribute whose value is
1
:
var container = document.querySelector("#userlist");
var matches = container.querySelectorAll("li[data-active='1']");
Once the
NodeList
of matching elements is returned, you can examine it just like any array. If the array is empty (that is, its
length
property is 0), then no matches were found.
Otherwise, you can simply use standard array notation to access the contents of the list. You can use any common looping statement, such as:
var highlightedItems = userList.querySelectorAll(".highlighted");
highlightedItems.forEach(function(userItem) {
deleteUser(userItem);
});
querySelectorAll()
behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results.
Consider this HTML, with its three nested
<div>
blocks.
<div class="outer">
<div class="select">
<div class="inner">
</div>
</div>
</div>
var select = document.querySelector('.select');
var inner = select.querySelectorAll('.outer .inner');
inner.length; // 1, not 0!
In this example, when selecting
.outer .inner
in the context the
<div>
with the class
select
, the element with the class
.inner
is still found, even though
.outer
is not a descendant of the base element on which the search is performed (
.select
). By default,
querySelectorAll()
only verifies that the last element in the selector is within the search scope.
:scope
pseudo-class restores the expected behavior, only matching selectors on descendants of the base element:
var select = document.querySelector('.select');
var inner = select.querySelectorAll(':scope .outer .inner');
inner.length; // 0
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
querySelectorAll
|
Chrome 1 | Edge 12 | Firefox 3.5 | IE 8 | Opera 10 | Safari 3.2 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 3 | Samsung Internet Android 1.0 |
完整支持
Element.querySelector()
and
Element.querySelectorAll()
Document.querySelector()
DocumentFragment.querySelector()
and
DocumentFragment.querySelectorAll()
ParentNode.querySelector()
and
ParentNode.querySelectorAll()
querySelector()
Document
alinkColor
all
anchors
applets
bgColor
body
characterSet
childElementCount
children
compatMode
contentType
currentScript
defaultView
designMode
dir
doctype
documentElement
documentURI
documentURIObject
domain
domConfig
嵌入
fgColor
firstElementChild
forms
fullscreen
fullscreenEnabled
head
height
hidden
图像
实现
lastElementChild
lastModified
lastStyleSheetSet
linkColor
链接
location
mozSyntheticDocument
onabort
onafterscriptexecute
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onbeforescriptexecute
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
onfullscreenchange
onfullscreenerror
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onoffline
ononline
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onvisibilitychange
onwheel
origin
plugins
popupNode
preferredStyleSheetSet
readyState
referrer
rootElement
脚本
scrollingElement
selectedStyleSheetSet
styleSheetSets
timeline
title
tooltipNode
URL
visibilityState
vlinkColor
width
xmlEncoding
xmlVersion
adoptNode()
append()
caretRangeFromPoint()
clear()
close()
createAttribute()
createCDATASection()
createComment()
createDocumentFragment()
createElement()
createElementNS()
createEntityReference()
createEvent()
createExpression()
createExpression()
createNodeIterator()
createNSResolver()
createNSResolver()
createProcessingInstruction()
createRange()
createTextNode()
createTouch()
createTouchList()
createTreeWalker()
enableStyleSheetsForSet()
evaluate()
evaluate()
execCommand()
exitFullscreen()
exitPointerLock()
getAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
hasFocus()
hasStorageAccess()
importNode()
mozSetImageElement()
open()
prepend()
queryCommandEnabled()
queryCommandSupported()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
registerElement()
releaseCapture()
replaceChildren()
requestStorageAccess()
write()
writeln()
animationcancel
animationend
animationiteration
animationstart
copy
cut
DOMContentLoaded
drag
dragend
dragenter
dragexit
dragleave
dragover
dragstart
drop
fullscreenchange
fullscreenerror
gotpointercapture
keydown
keypress
keyup
lostpointercapture
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointerlockchange
pointerlockerror
pointermove
pointerout
pointerover
pointerup
readystatechange
scroll
selectionchange
selectstart
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
visibilitychange
wheel
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument