元素 方法 querySelectorAll() returns a static (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.

注意: 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 backspace escaping, special care must be taken when writing string literals using these characters. See 转义特殊字符 了解更多信息。

返回值

A non-live NodeList containing one 元素 object for each descendant node that matches at least one of the specified selectors.

注意: 若指定 selectors include a CSS pseudo-element , the returned list is always empty.

异常

SyntaxError
The syntax of the specified selectors string is not valid.

范例

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"]`)];
					

Obtaining a list of matches

To obtain a NodeList of all of the <p> elements contained within the element "myBox" :

var matches = myBox.querySelectorAll("p");
					

This example returns a list of all <div> elements within "myBox" with a class of either " note " or " alert ":

var matches = myBox.querySelectorAll("div.note, div.alert");
					

Here, we get a list of the document's <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']");
					

Accessing the matches

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);
});
					

注意: NodeList is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. To convert it into an array, try Array.from(nodeList).

User notes

querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results.

HTML

Consider this HTML, with its three nested <div> blocks.

<div class="outer">
  <div class="select">
    <div class="inner">
    </div>
  </div>
</div>
					

JavaScript

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
					

规范

规范 状态 注释
DOM
The definition of 'ParentNode.querySelectorAll()' in that specification.
实时标准 Living standard
Selectors API Level 2
The definition of 'ParentNode.querySelectorAll()' in that specification.
过时 无变化
DOM4
The definition of 'ParentNode.querySelectorAll()' in that specification.
过时 初始定义
Selectors API Level 1
在该规范中的 document.querySelector() 定义。
过时 Original definition

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
querySelectorAll Chrome 1 Edge 12 Firefox 3.5 IE 9
9
部分支持 8 注意事项
querySelectorAll() is supported, but only for CSS 2.1 selectors.
Opera 10 Safari 3.1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 2 Samsung Internet Android 1.0

图例

完整支持

完整支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. DOM (文档对象模型)
  2. 元素
  3. 特性
    1. accessKey
    2. 属性
    3. childElementCount
    4. children
    5. classList
    6. className
    7. clientHeight
    8. clientLeft
    9. clientTop
    10. clientWidth
    11. currentStyle
    12. firstElementChild
    13. id
    14. innerHTML
    15. lastElementChild
    16. localName
    17. 名称
    18. namespaceURI
    19. nextElementSibling
    20. onfullscreenchange
    21. onfullscreenerror
    22. openOrClosedShadowRoot
    23. outerHTML
    24. part
    25. prefix
    26. previousElementSibling
    27. runtimeStyle
    28. scrollHeight
    29. scrollLeft
    30. scrollLeftMax
    31. scrollTop
    32. scrollTopMax
    33. scrollWidth
    34. shadowRoot
    35. slot
    36. tabStop
    37. tagName
  4. 方法
    1. after()
    2. animate()
    3. append()
    4. attachShadow()
    5. before()
    6. closest()
    7. computedStyleMap()
    8. createShadowRoot()
    9. getAnimations()
    10. getAttribute()
    11. getAttributeNames()
    12. getAttributeNode()
    13. getAttributeNodeNS()
    14. getAttributeNS()
    15. getBoundingClientRect()
    16. getClientRects()
    17. getElementsByClassName()
    18. getElementsByTagName()
    19. getElementsByTagNameNS()
    20. hasAttribute()
    21. hasAttributeNS()
    22. hasAttributes()
    23. hasPointerCapture()
    24. insertAdjacentElement()
    25. insertAdjacentHTML()
    26. insertAdjacentText()
    27. matches()
    28. msZoomTo()
    29. prepend()
    30. querySelector()
    31. querySelector()
    32. querySelectorAll()
    33. querySelectorAll()
    34. releasePointerCapture()
    35. remove()
    36. removeAttribute()
    37. removeAttributeNode()
    38. removeAttributeNS()
    39. replaceChildren()
    40. replaceWith()
    41. requestFullscreen()
    42. requestPointerLock()
    43. scroll()
    44. scrollBy()
    45. scrollIntoView()
    46. scrollIntoViewIfNeeded()
    47. scrollTo()
    48. setAttribute()
    49. setAttributeNode()
    50. setAttributeNodeNS()
    51. setAttributeNS()
    52. setCapture()
    53. setPointerCapture()
    54. toggleAttribute()
  5. 事件
    1. afterscriptexecute
    2. auxclick
    3. blur
    4. click
    5. compositionend
    6. compositionstart
    7. compositionupdate
    8. contextmenu
    9. copy
    10. cut
    11. dblclick
    12. DOMActivate
    13. DOMMouseScroll
    14. error
    15. focus
    16. focusin
    17. focusout
    18. fullscreenchange
    19. fullscreenerror
    20. gesturechange
    21. gestureend
    22. gesturestart
    23. keydown
    24. keypress
    25. keyup
    26. mousedown
    27. mouseenter
    28. mouseleave
    29. mousemove
    30. mouseout
    31. mouseover
    32. mouseup
    33. mousewheel
    34. MozMousePixelScroll
    35. msContentZoom
    36. MSGestureChange
    37. MSGestureEnd
    38. MSGestureHold
    39. MSGestureStart
    40. MSGestureTap
    41. MSInertiaStart
    42. MSManipulationStateChanged
    43. overflow
    44. paste
    45. scroll
    46. select
    47. show
    48. touchcancel
    49. touchend
    50. touchmove
    51. touchstart
    52. underflow
    53. webkitmouseforcechanged
    54. webkitmouseforcedown
    55. webkitmouseforceup
    56. webkitmouseforcewillbegin
    57. wheel
  6. 继承:
    1. 节点
    2. EventTarget
  7. DOM 相关页面
    1. AbortController
    2. AbortSignal
    3. AbstractRange
    4. Attr
    5. ByteString
    6. CDATASection
    7. CSSPrimitiveValue
    8. CSSValue
    9. CSSValueList
    10. CharacterData
    11. ChildNode
    12. 注释
    13. CustomEvent
    14. DOMConfiguration
    15. DOMError
    16. DOMErrorHandler
    17. DOMException
    18. DOMImplementation
    19. DOMImplementationList
    20. DOMImplementationRegistry
    21. DOMImplementationSource
    22. DOMLocator
    23. DOMObject
    24. DOMParser
    25. DOMPoint
    26. DOMPointInit
    27. DOMPointReadOnly
    28. DOMRect
    29. DOMString
    30. DOMTimeStamp
    31. DOMTokenList
    32. DOMUserData
    33. Document
    34. DocumentFragment
    35. DocumentType
    36. ElementTraversal
    37. Entity
    38. EntityReference
    39. 事件
    40. EventTarget
    41. HTMLCollection
    42. MutationObserver
    43. 节点
    44. NodeFilter
    45. NodeIterator
    46. NodeList
    47. NonDocumentTypeChildNode
    48. ProcessingInstruction
    49. PromiseResolver
    50. 范围
    51. StaticRange
    52. 文本
    53. TextDecoder
    54. TextEncoder
    55. TimeRanges
    56. TreeWalker
    57. TypeInfo
    58. USVString
    59. UserDataHandler
    60. XMLDocument