Note: 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);
DOMStringcontaining one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a
SyntaxErrorexception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them.
If you need a list of all elements matching the specified selectors, you should use
- The syntax of the specified selectors is invalid.
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.
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
\"). As the backslash is also an escape character in
<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,
<input> element with the name "login"
<input name="login"/>) located inside a
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
The definition of 'document.querySelector()' in that specification.
BCD tables only load in the browser