Please refer to the errata for this document, which may include some normative corrections.
See also translations.
Copyright © 2008 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
This specification defines the ElementTraversal
interface, which allows script navigation of the elements of a DOM tree, excluding all other nodes in the DOM, such as text nodes. It also provides an attribute to expose the number of child elements of an element. It is intended to provide a more convenient alternative to existing DOM navigation interfaces, with a low implementation footprint.
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 is the 22 December 2008 Recommendation of the Element Traversal specification.
This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.
The Web Applications (WebApps) Working Group has produced a test suite and implementation report to indicate the current level of implementation support for this specification, with passing results for all tests. There have been no changes since Proposed Recommendation.
Please send questions and comments regarding this specification to public-webapps@w3.org, the public email list for issues related to WebApps WG deliverables. This list is publicly archived, and acceptance of this archiving policy is requested automatically upon first post. To subscribe to this list send an email to public-webapps-request@w3.org with the word "subscribe" in the subject line.
This document has been produced by the Web Applications (WebApps) Working Group as part of the W3C Rich Web Clients Activity, following the procedures set out for the W3C Process.
The ElementTraversal
interface was originally published as part of the SVG Tiny 1.2 specification in the SVG namespace. At the request of the SVG, CDF, JCP, and other groups, it was transferred to the WebAPI WG, and migrated to DOM and DOM namespace as a generic facility. It was transferred again when the WebApps WG took responsibility for the deliverables of the WebAPI WG.
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 informative.
The DOM Level 1 Node
interface defines 11 node types, but most commonly authors wish to operate solely on nodeType
1
, the Element
node. Other node types include the Document
element and Text
nodes, which include whitespace and line breaks. DOM 1 node traversal includes all of these node types, which is often a source of confusion for authors and which requires an extra step for authors to confirm that the expected Element
node interfaces are available. This introduces an additional performance constraint.
ElementTraversal
is an interface which allows the author to restrict navigation to Element
nodes. It permits navigation from an element to its first element child, its last element child, and to its next or previous element siblings. Because the implementation exposes only the element nodes, the memory and computational footprint of the DOM representation can be optimized for constrained devices.
The DOM Level 1 Node
interface also defines the childNodes
attribute, which is a live list of all child nodes of the node; the childNodes
list has a length
attribute to expose the total number of child nodes of all nodeTypes
, useful for preprocessing operations and calculations before, or instead of, looping through the child nodes. The ElementTraversal
interface has a similar attribute, childElementCount
, that reports only the number of Element
nodes, which is often what is desired for such operations.
This specification does not include the complete list of attributes, methods, and other interfaces available on the Element
object. Additional interfaces are found in other specifications, notably the DOM Core specifications.
This section is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 [RFC2119]. For purposes of readability, these terms are not necessarily used in a case-sensitive manner in this document.
Sometimes, for readability, conformance requirements are phrased as requirements on elements, attributes, methods, interfaces, properties or functions. In all cases these are conformance requirements on implementations. A conforming implementation of this specification meets all requirements identified by the use of these terms, within the scope of its language bindings.
ElementTraversal
interfaceThis section is normative.
The ElementTraversal
interface is a set of read-only attributes which allow an author to easily navigate between elements in a document. In conforming implementations of Element Traversal, all objects that implement Element
must also implement the ElementTraversal
interface. Four of the attributes, firstElementChild
, lastElementChild
, previousElementSibling
, and nextElementSibling
, each provide a live reference to another element with the defined relationship to the current element, if the related element exists. The fifth attribute, childElementCount
, exposes the number of child elements of an element, for preprocessing before navigation. A conforming User Agent must implement all five attributes. A User Agent may implement similar interfaces in other specifications, but such implementation is not required for conformance to this specification, if the User Agent is designed for a minimal code footprint.
This interface must be implemented on all Element
s, regardless of their namespace. EntityReference nodes are not visible to the Element Traversal mechanism; if the tree-walker encounters an EntityReference node, it descends into it without informing the caller, and processes any children as if they had been present at the place where the entity node was found. Navigation must be irrespective of namespace, e.g. if an element in the HTML namespace is followed by element in the SVG namespace, the nextElementSibling
attribute on the HTML element will return the SVG element.
firstElementChild
Accessing this attribute of an element must return a reference to the first child node of that element which is of nodeType
1
, as an Element
object. If the element on which this attribute is accessed does not have any child nodes, or if none of those child nodes are element nodes, then this attribute must return null
.
lastElementChild
Accessing this attribute of an element must return a reference to the last child node of that element which is of nodeType
1
, as an Element
object. If the element on which this attribute is accessed does not have any child nodes, or if none of those child nodes are element nodes, then this attribute must return null
.
previousElementSibling
Accessing this attribute of an element must return a reference to the sibling node of that element which most immediately precedes that element in document order, and which is of nodeType
1
, as an Element
object. If the element on which this attribute is accessed does not have any preceding sibling nodes, or if none of those preceding sibling nodes are element nodes, then this attribute must return null
.
nextElementSibling
Accessing this attribute of an element must return a reference to the sibling node of that element which most immediately follows that element in document order, and which is of nodeType
1
, as an Element
object. If the element on which this attribute is accessed does not have any following sibling nodes, or if none of those following sibling nodes are element nodes, then this attribute must return null
.
childElementCount
Accessing this attribute of an element must return the current number of child nodes of that element which are of nodeType
1
. An implementation may store this number, or it may calculate it upon accessing this attribute, but the number must always represent the number of child element nodes at the time the attribute is accessed. Only immediate child nodes must be counted, e.g. elements which are child nodes of one of the child nodes of the element on which the attribute is accessed are not included in this count. If the element on which this attribute is accessed does not have any child nodes, or if none of those child nodes are element nodes, then this attribute must return 0.
This section is informative.
This section illustrates several ECMAScript [ECMA262] examples using Element Traversal.
previousElementSibling
This example demonstrates the utility of the previousElementSibling
attribute. The following code takes an element as a parameter, and returns the element's position in document order within its parent:
function findPosition( el ) { var pos = 0; // step through child elements in reverse order while ( null != el ) { // navigate to previous sibling el = el.previousElementSibling; pos++; } return pos; }
This example demonstrates the utility of the childElementCount
attribute. The following code takes an element as a parameter, and places each of its children equidistantly according to the available space:
function spaceChildren( el ) { // get count of element nodes var elCount = el.childElementCount; var eachWidth = window.innerWidth / (elCount + 1); // get first child element var childEl = el.firstElementChild; // set initial position var nextPos = eachWidth/2; // step through child elements one by one while ( childEl ) { // position child childEl.style.setProperty( 'position', 'absolute', '' ); childEl.style.setProperty( 'left', nextPos + 'px', '' ); childEl.style.setProperty( 'width', eachWidth + 'px', '' ); // increment position by width nextPos += eachWidth; // then navigate to next child element childEl = childEl.nextElementSibling; } }
This example contrasts ElementTraversal
with other DOM interfaces. The following script shows different methods of iterating through a DOM tree, given the following SVG fragment:
<g id='shapeGroup'> <rect id='rect1' x='5' y='5' width='310' height='220' rx='15' ry='15' fill='skyblue'/> <rect id='rect2' x='15' y='15' width='210' height='180' rx='15' ry='15' fill='cornflowerblue'/> <ellipse id='ellipse1' cx='90' cy='70' rx='50' ry='30' fill='yellow' stroke='orange'/> <path id='path1' stroke-width='15' stroke='orange' fill='none' stroke-linecap='round' d='M25,150 C180,180 290,0 400,140 S420,100 460,90'/> <text id='text1' x='0' y='0' font-size='35' fill='yellow' stroke='orange' stroke-width='2' stroke-linejoin='round' font-weight='bold'> <textPath id='textPath1' xlink:href="#path1">when life gives you lemons...</textPath></text> </g>
function walkTest( el ) { // get count of all nodes var nodeCount = el.childNodes.length; // get first child node var firstNode = el.firstChild; // get first child element var childEl = el.firstElementChild; // step through child elements one by one while ( childEl ) { // do something useful here... // then navigate to next child element childEl = childEl.nextElementSibling; } }
Where el is the 'g'
element with the 'id'
"shapeGroup"
, nodeCount will have the value 11
. firstNode will be a Text
node (nodeType
of 3
), and is not equivalent to the first assigned value of childEl, which is an Element
node (nodeType
of 1
) with the 'id'
"rect1"
. The while
loop will cycle 4 more times, iterating through the sibling Element
nodes, respectively "rect2"
, "ellipse1"
, "path1"
, and "text1"
. The last value of childEl will be null
, as "text1"
does not have a next element sibling, though it does have a next node sibling.
Note that an SVG 'text' element is not the same as a Text
node. Note also that the SVG 'textPath' child element of the 'text' element is not included in the iteration, as it is not a sibling of childEl.
This section is informative.
This specification provides an interface that has functional similarity to the DOM navigation attributes of DOM 1 Core, but operates only on element nodes, not other node types. The most comparable DOM 1 Core attributes are firstChild
, lastChild
, previousSibling
, nextSibling
, and nodeList.length
.
Document Object Model Level 2 Traversal & Range is a comprehensive document navigation specification, but may require more device and implementor resources than Element Traversal. As Element Traversal consists of an optimized subset of the functionality of DOM 2 Traversal, a user agent that implements both may do so in a way that leverages the functionality of Traversal.
This is a supplementary specification to DOM 3 Core.
This section is informative.
There are no known security considerations involved in the implementation or use of the ElementTraversal
interface. This section shall be revised if future security considerations are discovered.
interface ElementTraversal { readonly attribute ElementfirstElementChild
; readonly attribute ElementlastElementChild
; readonly attribute ElementpreviousElementSibling
; readonly attribute ElementnextElementSibling
; readonly attribute unsigned longchildElementCount
; };
firstElementChild
null
if this element has no child elements.lastElementChild
null
if this element has no child elements.previousElementSibling
null
if this element has no element sibling nodes that come before this one in the document tree.nextElementSibling
null
if this element has no element sibling nodes that come after this one in the document tree.childElementCount
0
if this element has no child nodes that are of nodeType
1
.Element
ElementTraversal
interface, Element
has all the properties and methods of Node
and Element
as defined in other DOM specifications, and in addition has the following properties:firstElementChild
Element
.lastElementChild
Element
.previousElementSibling
Element
.nextElementSibling
Element
.childElementCount
Number
.package org.w3c.dom; public interface ElementTraversal { Element getFirstElementChild(); Element getLastElementChild(); Element getPreviousElementSibling(); Element getNextElementSibling(); int getChildElementCount(); }
Various editorial changes and corrections and modifications to the examples were made from draft to draft.
The attribute childElementCount
was supplementary to the original proposal, for reasons stated in this specification.
ElementTraversal
interface in SVG.The editor would like to thank the following people for contributing to this specification: David Andersson, Robin Berjon, Jean-Yves Bitterlich, Sergiu Dumitriu, Daniel Glazman, Bjoern Hoehrmann, Kurosawa Takeshi, Chris Lilley, Charles McCathieNevile, Cameron McCormack, Simon Pieters, Nandini Ramani, Jonas Sicking, Andrew Sledd, Josh Soref, Anne van Kesteren, Boris Zbarsky, and Mohamed Zergaoui. The editor would additionally like to thank the SVG WG for producing the draft [SVGD] on which this was initially based.