Please refer to the errata for this document, which may include some normative corrections.
See also translations.
Copyright © 2006-2013 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.
Selectors, which are widely used in CSS, are patterns that match against
elements in a tree structure [SELECT][CSS21]. The Selectors API
specification defines methods for retrieving Element nodes from the DOM by matching against a group of
selectors. It is often desirable to perform DOM operations on a specific
set of elements in a document. These methods simplify the process of
acquiring specific elements, especially compared with the more verbose
techniques defined and used in the past.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This specification is a Superseded Recommendation. A newer specification exists that is recommended for new adoption in place of this specification.
For purposes of the W3C Patent Policy, this Superseded Recommendation has the same status as an active Recommendation; it retains licensing commitments and remains available as a reference for old — and possibly still deployed — implementations, but is not recommended for future implementation. New implementations should follow the Living Standard of the DOM specification.
The Web Applications (WebApps) Working Group has developed a comprehensive Selectors API test suite and has demonstrated interoperability of the features among implementations. Please see the Working Group's implementation report.
Please send comments about this document to public-webapps@w3.org (public archive) with [selectors-api] in the subject. (Please note that a different list was used until mid 2008, so some old messages are archived there instead).
This document was developed by the Web Applications Working Group. A complete list of changes to this document is available.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This section is non-normative.
This specification provides methods for selecting and testing elements
based on whether or not they match a given selector. With these methods,
it is easier to match a set of Element
nodes based on specific criteria, than having to subsequently filter the
result of calling other methods like getElementsByTagName().
This section is non-normative.
Some ECMAScript [ECMA-262-5.1] examples:
This is an example table written in HTML 4.01.
<table id="score">
<thead>
<tr>
<th>Test
<th>Result
<tfoot>
<tr>
<th>Average
<td>82%
<tbody>
<tr>
<td>A
<td>87%
<tr>
<td>B
<td>78%
<tr>
<td>C
<td>81%
</table>
In order to obtain the cells containing the results in the table, which
might be done, for example, to plot the values on a graph, there are at
least two approaches that may be taken. Using only the APIs from DOM
Level 2, it requires a script like the following that iterates through
each tr within each tbody in the
table to find the second cell of each row.
var table = document.getElementById("score");
var groups = table.tBodies;
var rows = null;
var cells = [];
for (var i = 0; i < groups.length; i++) {
rows = groups[i].rows;
for (var j = 0; j < rows.length; j++) {
cells.push(rows[j].cells[1]);
}
}
Alternatively, using the querySelectorAll() method, that
script becomes much more concise.
var cells = document.querySelectorAll("#score>tbody>tr>td:nth-of-type(2)");
Note that the script operates on the DOM and works independently from the syntax used to create the document. Thus this script will also work correctly for an equivalent table created from well-formed XHTML instead of HTML, or dynamically created and inserted into a document using DOM APIs.
All diagrams, examples and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words must, must not, should, may and recommended in the normative parts of this document are to be interpreted as described in RFC 2119 [RFC2119].
The following conformance classes are defined (and considered) by this specification:
The terminology used in this specification is that from Selectors [SELECT].
The following features are defined in the DOM Level 3 Core specification [DOM-LEVEL-3-CORE]:
Document
interface.
DocumentFragment
interface.
Element interface.
NodeList interface.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent.
The IDL used in this specification uses the syntax defined in Web IDL [DOM-BINDINGS].
The construction "Foo object", where Foo is
actually an interface, is sometimes used instead of the more accurate
"object implementing the Foo interface".
This section is non-normative.
Some implementations might have different levels of support for Selectors. If some implementations lack support for some selectors, then the use of such selectors will result in those implementations failing to return the expected results. Authors are advised to check for the DOM Exceptions thrown by these APIs and provide a fallback for graceful degradation.
This section is non-normative.
Extensions of the APIs defined in this specification are strongly discouraged. Implementors, Working Groups and other interested parties should discuss extensions on a relevant public forum, such as public-webapps@w3.org.
It is expected that implementing this specification introduces no new security risks for users.
If, at any time, the implementation detects a situation which would violate security policies, the implementation may abort and raise a security exception. If any other error condition occurs which is not covered directly by this or any other relevant specification, the implementation may abort and raise an appropriate, language-binding-specific or implementation-specific exception.
History theft is a potential privacy issue because the
:visited pseudo-class in Selectors [SELECT] allows authors to query
which links have been visited.
This is not a new problem, as it can already be exploited
using existing CSS and DOM APIs, such as getComputedStyle()
[DOM-LEVEL-2-STYLE].
In this example, vlinks will acquire a list of links that the user has visited. The author can then obtain the URIs and potentially exploit this knowledge.
var vlinks = document.querySelectorAll(":visited");
for (var i = 0; i < vlinks.length; i++) {
doSomethingEvil(vlinks[i].href);
}
As defined in Selectors ([SELECT], section 6.6.1), user agents may treat all links as unvisited links. It is recommended that implementations behave consistently with other uses of Selectors supported by the user agent.
The term first used in the definitions of the
methods defined in this specification means first in document
order. The term document order means a
depth-first pre-order traversal of the DOM tree or subtree in question.
The term context node refers to the node upon
which the method was invoked. The term subtrees
refers to the collection of elements that are descendants of the context node. The term matching Element node refers
to an Element node that matches the selector string (selectors) that
was passed to the method, according to the rules for matching elements
defined in Selectors [SELECT].
partial interface Document {
Element? querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};
partial interface DocumentFragment {
Element? querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};
partial interface Element {
Element? querySelector(DOMString selectors);
NodeList