W3C

Element Traversal Specification

W3C Working Draft 03 March 2008

This version:
http://www.w3.org/TR/2008/WD-ElementTraversal-20080303/
Latest version:
http://www.w3.org/TR/ElementTraversal/
Previous version:
http://www.w3.org/TR/2007/WD-ElementTraversal-20070727/
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

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 a Last Call Working Draft of a possible future W3C Recommendation of Element Traversal 1.0. The Last Call review period for this document extends until 03 April 2008. The public is invited to send comments or report errors on this document. Please send them to the public mailing public-webapi@w3.org (public archive) including the prefix'[Element Traversal LC]' in the subject line.

Publication as a Working Draft 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.

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.

This document was developed by the Web API WG (part of the Rich Web Clients Activity). The Working Group expects to advance this Working Draft to Recommendation Status.

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 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 Element Traversal. 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. For the purpose of Element Traversal, an entity reference node which represents an element must be treated as an element node. 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 evocation of 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 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 place 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;

   // 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', '' );
      
      //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 the all the attributes and methods of Node and Element as defined in other DOM specifications, and in addition has the attributes defined below.
The Element object has the following attributes:
firstElementChild
This read-only attribute is of type Element.
lastElementChild
This read-only attribute is of type Element.
previousElementSibling
This read-only attribute is of type Element.
nextElementSibling
This read-only attribute is of type Element.
childElementCount
This read-only attribute is of type Number.

C. Java Language Binding

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

public interface ElementTraversal 
{
    public Element getFirstElementChild();

    public Element getLastElementChild();

    public Element getPreviousElementSibling();

    public Element getNextElementSibling();

    public 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, 1997. The specification for how to use English to specify normativity, as if it were a technical language. Available at http://rfc.net/rfc2119.html
[DOM1Core] Document Object Model - Level 1 Core
Available at http://www.w3.org/TR/REC-DOM-Level-1/
[ECMA262] ECMAScript Language Specification, 3rd edition
Available at http://www.ecma-international.org/publications/standards/Ecma-262.htm

Informative references

[SVGD] The proposed ElementTraversal interface in SVG
Available at http://www.w3.org/TR/SVGMobile12/svgudom.html#svg__ElementTraversal
[DOM2TR] The DOM 2 Traversal and Range Specification
Available at http://www.w3.org/TR/DOM-Level-2-Traversal-Range/
[DOM3Core] Document Object Model - Level 3 Core
Available at http://www.w3.org/TR/DOM-Level-3-Core/

F. Acknowledgments

The editor would like to thank the following people for contributing to this specification: Robin Berjon, Chris Lilley, Nandini Ramani, Andrew Sledd, Charles McCathieNevile, Jean-Yves Bitterlich, Bjoern Hoehrmann, Simon Pieters, Cameron McCormack, and Mohamed Zergaoui. The editor would additionally like to thank the SVG WG for producing the draft [SVGD] on which this was initially based.