W3C

Element Traversal Specification

W3C Candidate Recommendation 13 August 2008

This version:
http://www.w3.org/TR/2008/CR-ElementTraversal-20080813/
Latest version:
http://www.w3.org/TR/ElementTraversal/
Previous version:
http://www.w3.org/TR/2008/WD-ElementTraversal-20080303/
Editor:
Doug Schepers (W3C, formerly Vectoreal) <schepers@w3.org>

Abstract

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.

Status of this Document

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

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 13 August 2008 Candidate Recommendation of the Element Traversal specification. W3C publishes a Candidate Recommendation to indicate that the document is believed to be stable and to encourage implementation by the developer community. The Web Applications (WebApps) Working Group expects to request that the Director advance this document to Proposed Recommendation once the Working Group has developed a comprehensive Element Traversal test suite, and demonstrated at least two interoperable implementations for each test. The WebApps Working Group expects to show these implementations by October 2008, based on known implementations. The Working Group does not plan to request to advance to Proposed Recommendation prior to 01 October 2008.

This is a W3C Candidate Recommendation. The Last Call Working Draft for this specification resulted in a number of Last Call comments which have all been addressed by the WebApps Working Group, a list of which can be found in the Disposition of Comments.

Please send comments 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 WebApps Working Group expects to advance this Working Draft to Recommendation Status.

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.

Table of Contents

1. Introduction

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.

1.1. Not in This Specification

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.

1.2. Conformance

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.

2. ElementTraversal interface

This 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 Elements, 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.

2.1. 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.

2.2. 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.

2.3. 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.

2.4. 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.

2.5. 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.

3. Examples of usage

This section is informative.

This section illustrates several ECMAScript [ECMA262] examples using Element Traversal.

3.1. Example of 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;
}

3.2. Example of Precalculating Values and Looping Through Elements

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;
   }
}

3.3. Example of Comparison with Other DOM Interfaces

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.

4. Relationship to other DOM specifications

This section is informative.

4.1. DOM Level 1 Core

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.

4.2. DOM Level 2 Traversal & Range

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.

4.3. DOM Level 3 Core

This is a supplementary specification to DOM 3 Core.

5. Security Considerations

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.

A. IDL Definitions

IDL Definition
interface ElementTraversal
{
   readonly attribute Element        firstElementChild;
   readonly attribute Element        lastElementChild;
   readonly attribute Element        previousElementSibling;
   readonly attribute Element        nextElementSibling;
   readonly attribute unsigned long  childElementCount;
};
No defined constants
Attributes
firstElementChild
Returns the first child element node of this element. null if this element has no child elements.
lastElementChild
Returns the last child element node of this element. null if this element has no child elements.
previousElementSibling
Returns the previous sibling element node of this element. null if this element has no element sibling nodes that come before this one in the document tree.
nextElementSibling
Returns the next sibling element node of this element. null if this element has no element sibling nodes that come after this one in the document tree.
childElementCount
Returns the current number of element nodes that are children of this element. 0 if this element has no child nodes that are of nodeType 1.
No defined methods

B. ECMAScript Language Binding

Object Element
In a User Agent which implements the 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
This read-only property is of type Element.
lastElementChild
This read-only property is of type Element.
previousElementSibling
This read-only property is of type Element.
nextElementSibling
This read-only property is of type Element.
childElementCount
This read-only property is of type Number.

C. Java Language Binding

org/w3c/dom/ElementTraversal.java:
package org.w3c.dom;

public interface ElementTraversal 
{
    Element getFirstElementChild();

    Element getLastElementChild();

    Element getPreviousElementSibling();

    Element getNextElementSibling();

    int getChildElementCount();
}

D. Change History

Various editorial changes and corrections and modifications to the examples are made from draft to draft.

The attribute childElementCount was supplementary to the original proposal, for reasons stated in this specification.

E. References

Normative references

[RFC2119]
Key words for use in RFCs to indicate Requirement Levels, S. Bradner, March 1997. The specification for how to use English as if it were a technical language to indicate normative requirements.
[DOM1Core]
Document Object Model - Level 1 Core, V. Apparao, S. Byrne, M. Champion, S. Isaacs, I. Jacobs, A. Le Hors, G. Nicol, J. Robie, R. Sutor, C. Wilson, L. Wood, Editors. World Wide Web Consortium, 1 October 1998. A standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them.
[ECMA262]
Standard ECMA-262, 3rd edition. ECMA International, December 1999. The specification for the ECMAScript language, of which JavaScript is a dialect.

Informative references

[SVGD]
The SVG Micro DOM (uDOM), O. Andersson, R. Berjon, E. Dahlström, A. Emmons, J. Ferraiolo, V. Hardy, S. Hayman, D. Jackson, C. Lilley, A. Neumann, C. Northway, A. Quint, N. Ramani, D. Schepers, A. Shellshear, Editors. World Wide Web Consortium, 10 August 2006. The proposed ElementTraversal interface in SVG.
[DOM2TR]
Document Object Model (DOM) Level 2 Traversal and Range Specification, J. Kesselman, J. Robie, M. Champion, P. Sharpe, V. Apparao, L. Wood, Editors. World Wide Web Consortium, 13 November 2000. A set of platform- and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.
[DOM3Core]
Document Object Model (DOM) Level 3 Core Specification, A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne, Editors. World Wide Web Consortium, 07 April 2004. A platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents.

F. Acknowledgments

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.