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
The syntax of the specified selectors string is not valid.

范例

Obtaining a list of matches

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

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

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 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

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. DOM (文档对象模型)
  2. Document
  3. 构造函数
    1. Document()
  4. 特性
    1. alinkColor
    2. all
    3. anchors
    4. applets
    5. bgColor
    6. body
    7. characterSet
    8. childElementCount
    9. children
    10. compatMode
    11. contentType
    12. currentScript
    13. defaultView
    14. designMode
    15. dir
    16. doctype
    17. documentElement
    18. documentURI
    19. documentURIObject
    20. domain
    21. domConfig
    22. 嵌入
    23. fgColor
    24. firstElementChild
    25. forms
    26. fullscreen
    27. fullscreenEnabled
    28. head
    29. height
    30. hidden
    31. 图像
    32. 实现
    33. lastElementChild
    34. lastModified
    35. lastStyleSheetSet
    36. linkColor
    37. 链接
    38. location
    39. mozSyntheticDocument
    40. onabort
    41. onafterscriptexecute
    42. onanimationcancel
    43. onanimationend
    44. onanimationiteration
    45. onauxclick
    46. onbeforescriptexecute
    47. onblur
    48. oncancel
    49. oncanplay
    50. oncanplaythrough
    51. onchange
    52. onclick
    53. onclose
    54. oncontextmenu
    55. oncuechange
    56. ondblclick
    57. ondurationchange
    58. onended
    59. onerror
    60. onfocus
    61. onformdata
    62. onfullscreenchange
    63. onfullscreenerror
    64. ongotpointercapture
    65. oninput
    66. oninvalid
    67. onkeydown
    68. onkeypress
    69. onkeyup
    70. onload
    71. onloadeddata
    72. onloadedmetadata
    73. onloadend
    74. onloadstart
    75. onlostpointercapture
    76. onmousedown
    77. onmouseenter
    78. onmouseleave
    79. onmousemove
    80. onmouseout
    81. onmouseover
    82. onmouseup
    83. onoffline
    84. ononline
    85. onpause
    86. onplay
    87. onplaying
    88. onpointercancel
    89. onpointerdown
    90. onpointerenter
    91. onpointerleave
    92. onpointermove
    93. onpointerout
    94. onpointerover
    95. onpointerup
    96. onreset
    97. onresize
    98. onscroll
    99. onselect
    100. onselectionchange
    101. onselectstart
    102. onsubmit
    103. ontouchcancel
    104. ontouchstart
    105. ontransitioncancel
    106. ontransitionend
    107. onvisibilitychange
    108. onwheel
    109. origin
    110. plugins
    111. popupNode
    112. preferredStyleSheetSet
    113. readyState
    114. referrer
    115. rootElement
    116. 脚本
    117. scrollingElement
    118. selectedStyleSheetSet
    119. styleSheetSets
    120. timeline
    121. title
    122. tooltipNode
    123. URL
    124. visibilityState
    125. vlinkColor
    126. width
    127. xmlEncoding
    128. xmlVersion
  5. 方法
    1. adoptNode()
    2. append()
    3. caretRangeFromPoint()
    4. clear()
    5. close()
    6. createAttribute()
    7. createCDATASection()
    8. createComment()
    9. createDocumentFragment()
    10. createElement()
    11. createElementNS()
    12. createEntityReference()
    13. createEvent()
    14. createExpression()
    15. createExpression()
    16. createNodeIterator()
    17. createNSResolver()
    18. createNSResolver()
    19. createProcessingInstruction()
    20. createRange()
    21. createTextNode()
    22. createTouch()
    23. createTouchList()
    24. createTreeWalker()
    25. enableStyleSheetsForSet()
    26. evaluate()
    27. evaluate()
    28. execCommand()
    29. exitFullscreen()
    30. exitPointerLock()
    31. getAnimations()
    32. getBoxObjectFor()
    33. getElementById()
    34. getElementsByClassName()
    35. getElementsByName()
    36. getElementsByTagName()
    37. getElementsByTagNameNS()
    38. hasFocus()
    39. hasStorageAccess()
    40. importNode()
    41. mozSetImageElement()
    42. open()
    43. prepend()
    44. queryCommandEnabled()
    45. queryCommandSupported()
    46. querySelector()
    47. querySelector()
    48. querySelectorAll()
    49. querySelectorAll()
    50. registerElement()
    51. releaseCapture()
    52. replaceChildren()
    53. requestStorageAccess()
    54. write()
    55. writeln()
  6. 事件
    1. animationcancel
    2. animationend
    3. animationiteration
    4. animationstart
    5. copy
    6. cut
    7. DOMContentLoaded
    8. drag
    9. dragend
    10. dragenter
    11. dragexit
    12. dragleave
    13. dragover
    14. dragstart
    15. drop
    16. fullscreenchange
    17. fullscreenerror
    18. gotpointercapture
    19. keydown
    20. keypress
    21. keyup
    22. lostpointercapture
    23. paste
    24. pointercancel
    25. pointerdown
    26. pointerenter
    27. pointerleave
    28. pointerlockchange
    29. pointerlockerror
    30. pointermove
    31. pointerout
    32. pointerover
    33. pointerup
    34. readystatechange
    35. scroll
    36. selectionchange
    37. selectstart
    38. touchcancel
    39. touchend
    40. touchmove
    41. touchstart
    42. transitioncancel
    43. transitionend
    44. transitionrun
    45. transitionstart
    46. visibilitychange
    47. wheel
  7. 继承:
    1. 节点
    2. EventTarget
  8. 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. DocumentFragment
    34. DocumentType
    35. 元素
    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