Document
方法
querySelector()
返回第一
元素
在文档中匹配指定选择器或选择器组。若未找到匹配,
null
被返回。
注意 : The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.
element = document.querySelector(selectors);
DOMString
containing one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a
SYNTAX_ERR
exception is thrown. See
使用选择器定位 DOM 元素
for more about selectors and how to manage them.
注意: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters. See 转义特殊字符 了解更多信息。
HTMLElement
object representing the first element in the document that matches the specified set of
CSS 选择器
,或
null
is returned if there are no matches.
If you need a list of all elements matching the specified selectors, you should use
querySelectorAll()
代替。
SYNTAX_ERR
If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned.
CSS 伪元素 will never return any elements, as specified in the 选择器 API .
To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("
\
"). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it
twice
(once for the JavaScript string, and another time for
querySelector()
):
<div id="foo\bar"></div>
<div id="foo:bar"></div>
<script>
console.log('#foo\bar'); // "#fooar" (\b is the backspace control character)
document.querySelector('#foo\bar'); // Does not match anything
console.log('#foo\\bar'); // "#foo\bar"
console.log('#foo\\\\bar'); // "#foo\\bar"
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>
In this example, the first element in the document with the class "
myclass
" is returned:
var el = document.querySelector(".myclass");
Selectors can also be really powerful, as demonstrated in the following example. Here, the first
<input>
element with the name "login" (
<input name="login"/>
) located inside a
<div>
whose class is "user-panel main" (
<div class="user-panel main">
) in the document is returned:
var el = document.querySelector("div.user-panel.main input[name='login']");
As all CSS selector strings are valid, you can also negate selectors:
var el = document.querySelector("div.user-panel:not(.main) input[name='login']");
This will select an input with a parent div with the
user-panel
class but not the
main
类。
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
在该规范中的 document.querySelector() 定义。 |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
querySelector
|
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()
Document.querySelectorAll()
Element.querySelectorAll()
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