草案
本页尚未完工.
ParentNode
mixin 将 querySelector()
方法定义为返回一个 Element
表示与指定的选择器组匹配的第一个元素,这些选择器是调用该方法的对象的后代。
如果您需要与选择器列表匹配的所有元素,使用 querySelectorAll()
。
Note: 该方法的实现为 Document.querySelector()
, DocumentFragment.querySelector()
和 Element.querySelector()
.
语法
element = parentNode.querySelector(selectors);
参数
selectors
DOMString
包含一个或多个要匹配的选择器。该字符串必须是浏览器支持的compound selector list ;如果不是, 会抛出SyntaxError
异常. 查阅 Locating DOM elements using selectors 获取有关选择器使用的更多信息. 可以通过使用逗号分隔多个选择器来指定它们。
Note: 必须使用反斜杠字符转义不属于CSS语法的字符。由于JavaScript也使用退格转义,因此在使用这些字符编写字符串文字是必须特别小心。查阅 Escaping special characters 获取更多信息。
返回值
第一个 Element
匹配至少一个指定的选择器,如果没有找到这样的元素,返回 null
。
Note: 如果指定的选择器包含 CSS pseudo-element, 则返回值始终为 null
.
Exceptions
SyntaxError
- 指定的
selectors
字符串语法无效。
Specifications
Specification | Status | Comment |
---|---|---|
DOM ParentNode.querySelector() |
Living Standard | Living standard |
Selectors API Level 2 ParentNode.querySelector() |
Obsolete | No change |
DOM4 ParentNode.querySelector() |
Obsolete | Initial definition |
Selectors API Level 1 document.querySelector() |
Obsolete | Original definition |
Browser compatibility
BCD tables only load in the browser
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.
See also
- Locating DOM elements using selectors
- Code snippets for
querySelector()
- Attribute selectors in the CSS Guide
- Attribute selectors in the MDN Learning Area
- This method is available as
Element.querySelector()
,Document.querySelector()
, andDocumentFragment.querySelector()