DocumentFragment.querySelector() method returns the first element, or null if no matches are found, within the DocumentFragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.

If the selector matches an ID and this ID is erroneously used several times in the document, it returns the first matching element.

If the selectors specified in parameter are invalid a DOMException 采用 SYNTAX_ERR value is raised.

句法

element = documentfragment.querySelector(selectors);
					

参数

selectors
DOMString containing one or more CSS selectors separated by commas.

范例

基本范例

In this basic example, the first element in the DocumentFragment with the class " myclass " is returned:

var el = documentfragment.querySelector(".myclass");
					

CSS syntax and the method's argument

The string argument pass to querySelector must follow the CSS syntax. To match ID or selectors that do not follow the CSS syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash:

<div id="foo\bar"></div>
<div id="foo:bar"></div>
<script>
document.querySelector('#foo\bar')    // Does not match anything
document.querySelector('#foo\\\\bar') // Match the first div
document.querySelector('#foo:bar')     // Does not match anything
document.querySelector('#foo\\:bar')   // Match the second div
</script>
					

规范

规范 状态 注释
Selectors API Level 2
The definition of 'DocumentFragment.querySelector' in that specification.
过时 无变化自 Selectors API Level 1
Selectors API Level 1
The definition of 'DocumentFragment.querySelector' in that specification.
过时 初始定义。

浏览器兼容性

The compatibility table in 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
querySelector Chrome 1 Edge 12 Firefox 3.5 IE 9 Opera 10 Safari 3.2 WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android 10.1 Safari iOS 3.2 Samsung Internet Android Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: