querySelector Method
.gif)
Note: This documentation is preliminary and is subject to change.
Retrieves the first Document Object Model (DOM) element node from descendants of the starting element node that match any selector within the supplied selector string.
Syntax
pel = object.querySelector(v)
Parameters
v Required. The selector string.
Return Value
A DOM element node, or null if the search cannot find an element that matches the selector string.
Remarks
The scope of the returned element nodes is limited to the descendants of the starting element node—the scope is always a subset of the document. This is in contrast to the IDocumentSelector methods, where the scope of the search is always the entire document.
This method will not yield the DOM element node that the method was called upon. For example,
div.querySelector("p span")will never return the DIV element that it starts with.Selectors are described in detail in W3C Selectors
.
Example
This example illustrates how the selectors in the selector string are scoped to the entire document. The variable
econtains the span even though the provided selector references the P element, which is outside the scope of the starting DIV element.<html> <meta http-equiv="X-UA-Compatible" content="IE=8"> <!-- To limit the search to descendants of an element only, --> <!-- call the selectors API on the specific element of interest. --> <body> <p> <div id="apple"> <span>Some are sauce, some are pie.</span> </div> </p> <script> var div = document.getElementById("apple"); var e = div.querySelector("p span"); // 'e' will select the span. var f = div.querySelector("p div"); // 'f' will be null because the div is not a descendent of 'div' </script> </body> </html>
Standards Information
This method is defined in Selectors API (W3C Working Draft)
.
Applies To
A, ADDRESS, B, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, DD, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FORM, hn, HTML, I, IMG, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, ISINDEX, KBD, LABEL, LEGEND, LI, LISTING, MARQUEE, MENU, NOBR, OL, P, PLAINTEXT, PRE, S, SAMP, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP
See Also
W3C Selectors API
, W3C Selectors
, querySelectorAll, IElementSelector, IDocumentSelector
.