Syntax
element = document.querySelector(selectors);
where
selectors
is a string containing one or more CSS selectors separated by commas.
Example
In this example, the first element in the document with the class "
myclass
" is returned:var el = document.querySelector(".myclass");
Returns
null
if no matches are found; otherwise, it returns the first matching element.
If the selector matches an ID and this ID is erroneously used several times in the document, it returns the first matching element.
Throws a
SYNTAX_ERR
exception if the specified group of selectors is invalid.querySelector()
was introduced in the Selectors API.
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 a colon 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>
No comments:
Post a Comment