Selectors, which are widely used in CSS, are patterns that match againstelements in a tree structure[SELECT][CSS21]. The Selectors APIspecification defines methods for retrievingElementnodes from theDOMby matching against a group ofselectors. It is often desirable to perform DOM operations on a specificset of elements in a document. These methods simplify the process ofacquiring specific elements, especially compared with the more verbosetechniques defined and used in the past.
Status of this Document
This section describes the status of this document at the time ofits publication. Other documents may supersede this document. A list ofcurrent W3C publications and the latest revision of this technical reportcan be found in theW3C technical reportsindexat http://www.w3.org/TR/.
This specification is aSupersededRecommendation. A newer specification exists that is recommendedfor new adoption in place of this specification.
For purposes of the W3C Patent Policy, this SupersededRecommendation has the same status as an active Recommendation; itretains licensing commitments and remains available as a referencefor old — and possibly still deployed — implementations, but isnot recommended for future implementation. New implementationsshould follow theLivingStandardof the DOM specification.
Please send comments about this document topublic-webapps@w3.org(publicarchive) with[selectors-api]in the subject. (Please notethat a different list was used until mid 2008, so some old messages arearchived thereinstead).
This specification provides methods for selecting and testing elementsbased on whether or not they match a given selector. With these methods,it is easier to match a set ofElementnodes based on specific criteria, than having to subsequently filter theresult of calling other methods likegetElementsByTagName().
In order to obtain the cells containing the results in the table, whichmight be done, for example, to plot the values on a graph, there are atleast two approaches that may be taken. Using only the APIs from DOMLevel 2, it requires a script like the following that iterates througheachtrwithin eachtbodyin thetableto 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 thequerySelectorAll()method, thatscript 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 fromthe syntax used to create the document. Thus this script will also workcorrectly for an equivalent table created from well-formed XHTML insteadof HTML, or dynamically created and inserted into a document using DOMAPIs.
twoConformance Requirements
All diagrams, examples and notes in this specification arenon-normative, as are all sections explicitly marked non-normative.Everything else in this specification is normative.
The key wordsmust,must not,should,mayandrecommendedin the normative parts of this document are tobe interpreted as described in RFC 2119[RFC2119].
The following conformance classes are defined (and considered) by thisspecification:
conforming user agent
A user agent that implements the interfaces described in thisspecification and conforms to allmust-level criteriathat apply to implementations.
conforming application
An application that uses the interfaces defined in this specificationand conforms to allmust-level criteria that apply toapplications.
2.1.Terminology andConventions
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]:
Documentinterface.
DocumentFragmentinterface.
Elementinterface.
NodeListinterface.
Conformance requirements phrased as algorithms or specific stepsmaybe implemented in any manner, so long as the end resultis equivalent.
The IDL used in this specification uses the syntax defined in Web IDL[DOM-BINDINGS].
The construction "Fooobject", whereFooisactually an interface, is sometimes used instead of the more accurate"object implementing theFoointerface".
threeInteroperabilityConsiderations
This section is non-normative.
Some implementations might have different levels of support forSelectors. If some implementations lack support for some selectors, thenthe use of such selectors will result in those implementations failing toreturn the expected results. Authors are advised to check for the DOMExceptions thrown by these APIs and provide a fallback for gracefuldegradation.
3.1.Extensibility
This section is non-normative.
Extensions of the APIs defined in this specification arestronglydiscouraged. Implementors, Working Groups and other interestedparties should discuss extensions on a relevant public forum, such aspublic-webapps@w3.org.
fourSecurity Considerations
It is expected that implementing this specification introduces no newsecurity risks for users.
If, at any time, the implementation detects a situation which wouldviolate security policies, the implementationmayabortand raise a security exception. If any other error condition occurs whichis not covered directly by this or any other relevant specification, theimplementationmayabort and raise an appropriate,language-binding-specific or implementation-specific exception.
fivePrivacy Considerations
History theft is a potential privacy issue because the:visitedpseudo-class in Selectors[SELECT]allows authors to querywhich links have been visited.
This is not a new problem, as it can already be exploitedusing existing CSS and DOM APIs, such asgetComputedStyle()[DOM-LEVEL-2-STYLE].
In this example,vlinkswill acquire a list of links thatthe user has visited. The author can then obtain the URIs and potentiallyexploit this knowledge.
var vlinks = document.querySelectorAll(":visited");for (var i = 0; i < vlinks.length; i++) {doSomethingEvil(vlinks[i].href);}
Asdefined inSelectors([SELECT], section 6.6.1), useragentsmaytreat all links as unvisited links. It isrecommendedthat implementations behave consistently withother uses of Selectors supported by the user agent.
sixThe APIs
The termfirstused in the definitions of themethods defined in this specification meansfirst in documentorder. The termdocument ordermeans adepth-first pre-order traversal of the DOM tree or subtree in question.The termcontext noderefers to the node uponwhich the method was invoked. The termsubtreesrefers to the collection of elements that are descendants of thecontext node. The termmatchingElementnoderefersto anElementnode that matches theselector string(selectors) thatwas passed to the method, according to the rules for matching elementsdefined in Selectors[SELECT].
Letparsed selectorbe the result of running the algorithmtoparse a selectorwithselectorsas the input.
The implementation must then run the algorithm toevaluate a selectoragainst elementnodes in the specifiedtreeorsubtreesusingparsed selectoras theselector to return the required result for the invoked method.
TheNodeListobject returned by thequerySelectorAll()methodmustbe static,notlive([DOM-LEVEL-3-CORE],section 1.1.1). Subsequent changes to the structure of the underlyingdocumentmust notbe reflected in theNodeListobject. This means that theobject will instead contain a list of matchingElementnodes that were in the documentat the time the list was created.
6.3.Grammar
Aselector stringis a list of one or moregroup ofselectors([SELECT], section 5) thatmaybe surrounded by whitespace and matches thedom_selectors_groupproduction.
Implementers are advised that ifnullorundefinedare passed as the value of theselectorsparameter, they are to be handled as defined in WebIDL[DOM-BINDINGS]. Authors areadvised to avoid passing these values.
Authors are advised that while the use of pseudo-elements inselectors is permitted, they will not match any elements in the document,and thus would not result in any elements being returned. Therefore,authors are advised to avoid the use of pseudo-elements in selectors thatare passed to the methods defined in this specification.
6.4.ProcessingSelectors
The steps toparse a selectorare asfollows:
Letselectorsbe theselectorstringinput to this algorithm.
Letresultbe the group of selectors returned as a resultof parsing theselectorsaccording to the grammar fordom_selectors_groupdefined above.
This specification does not provide support for resolvingarbitrary namespace prefixes. However, support for a namespace prefixresolution mechanism may be considered for inclusion in a future versionof this specification.
Anamespace prefix needs to be resolvedif thenamespace component is neither empty (e.g.|div),representing the null namespace, or an asterisk (e.g.*|div),representing any namespace. Since the asterisk or empty namespace prefixdo not need to be resolved, implementations that support the namespacesyntax in Selectorsmustsupport these.[SELECT]
sevenExamples
The following examples make use of this sample XHTML document.
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Selectors API Example</title></head><body><div id="foo"><p class="warning">This is a sample warning</p><p class="error">This is a sample error</p></div><div id="bar"><p>...</p></div></body></html>
The methods accept a group of selectors (comma separated) as theargument. The following example would select allpelementsin the document that have a class of either "error" or"warning".
var alerts = document.querySelectorAll("p.warning, p.error");
ThequerySelector()methodsalso accept a group of selectors and they will return the first element(if any) that matches any of the selectors in the group.
var x = document.querySelector("#foo, #bar");
xwould contain the first element in the document with an IDof eitherfooorbar, ornullifthere is no such element. In the sample document above, it would selectthedivelement with the ID offoobecause itis first indocument order. The order ofthe selectors used in the parameter has no effect and would have the sameresult if the order were reversed, as in:
var x = document.querySelector("#bar, #foo");
The methods can also be invoked on elements. In the following example,assume the event handler is registered on an element, and thus the methodis invoked on the target element of the event.
function handle(evt) {var x = evt.target.querySelector("span");...// Do something with x}
Even though the method is invoked on an element, selectors are stillevaluated in the context of the entire document. In the followingexample, the method will still match thedivelement's childpelement, even though thebodyelement is nota descendant of thedivelement itself.
var div = document.getElementById("bar");var p = div.querySelector("body p");
Given this sample fragment that contains a list as a navigation menu:
The following example selects all thelielements anddemonstrates how to iterate through the collection in aNodeList.
var lis = document.querySelectorAll("ul.nav>li");for (var i = 0; i < lis.length; i++) {process(lis.item(i));}
In ECMAScript, the language binding also allowsNodeLists to be addressed using thearray notation, so that loop could be rewritten like this:
for (var i = 0; i < lis.length; i++) {process(lis[i]);}
Since theNodeListobjectsreturned by these methods are not live, changes to the DOM do not affectthe content of the list. Consider theprocess()functioncalled in the previous examples is defined as follows:
function process(elmt) {elmt.parentNode.removeChild(elmt);}
This would cause each selected element to be removed from the DOM, buteach element will remain in theNodeList. If the list were a liveNodeList, removing an item from the DOMwould also remove the element from the list and adjust the indexes ofsubsequent elements. That would have adverse effects upon the loopbecause not all selected elements would be processed.
In documents comprising elements from multiple namespaces, it'spossible that some elements from different namespaces share the samelocal name. Since this API does not natively support a namespaceresolution mechanism for selectors, obtaining a list of such elementsfrom a specific namespace, excluding all others, requires additionalprocessing to filter the result. The following example illustrates adocument containingvideoelements from both the SVG andXHTML namespaces.
The following script demonstrates how to first select thevideoelements and then filter out the unwanted elementsbased on their namespace.
var elms = document.querySelectorAll("svg video");var result = new Array();var svgns = "http://www.w3.org/2000/svg"for(var i = 0; i < elms.length; i++) {if(elms[i].namespaceURI == svgns) {result.push(elms[i]);}}
The editors would like to thank to the following people who havecontributed to this specification (ordered on first name):
Adam van den Hoven, Alan Gresley, Alex Russell, Arthur Barstow, AryehGregor, Björn Höhrmann, Boris Zbarsky, Cameron McCormack, CharlesMcCathieNevile, Chris Wilson, Christophe Jolif, Daniel Glazman, DanielSchierbeck, Dave Massy, David "liorean" Andersson, David Greenspan, DavidHåsäther, Dean Jackson, Doug Schepers, Erik Dahlström, Francois Remy,Hallvord R. M. Steen, Henri Sivonen, Ian Hickson, Ivan Enderlin, Jean-YvesBitterlich, Jim Ley, João Eiras, John Resig, Jon Ferraiolo, JonasSicking, Jorgen Horstink, Kang-Hao (Kenny) Lu, Karl Dubost, KartikayaGupta, L. David Baron, Maciej Stachowiak, Magnus Kristiansen, MaratTanalin, Martijn, Masataka Yakura, Mihai Sucan, Mohamed Zergaoui, NicholasC. Zakas, Nicolas Mendoza, Norbert Lindenberg, Philip Taylor, RobertSayre, Robin Berjon, Sander, Sergey Ilinsky, Simon Pieters, StevenPemberton, Stewart Brodie Tab Atkins Jr., Tarquin Wilton-Jones, TravisLeithead, and William J. Edney
Special thanks to John Resig and Øyvind Stenhaug for their significantcontributions to the testsuite.
Thanks to all those who have helped to improve this specification bysending suggestions and corrections.