DOM2 Traversal - Description

The DOM2 Traversal module defines the NodeFilter, NodeIterator and TreeWalker interfaces. These interfaces allow you to quickly retrieve groups of nodes that satisfy almost any criteria. In cases where getElementById() and getElementsByTagName() won't do, a NodeIterator or a TreeWalker will (for instance, if you want to attach the same event handler to all elements with a given class name). NodeIterators and TreeWalkers differ in how they preserve relationships between the filtered nodes (NodeIterators return a list while TreeWalkers maintain the tree structure of the document) and how they react to changes to the underlying document (see the W3C offical Traversal documentation for more).

Only Mozilla implements any of the Traversal module - the NodeFilter and TreeWalker interfaces. This script extends the NodeFilter and TreeWalker interfaces to work on IE5+. The NodeFilter interface is basically just a set of constants. The TreeWalker is a bit more involved and this script includes all the methods and properties mentioned in the W3C specifications (see the usage instructions). TreeWalkers built with this script also react dynamically to changes to the underlying document structure and to their filters as officially prescribed.

Though they have a simpler interface, NodeIterators react in complex ways when the underlying document structure changes. So much so that it is not possible to mimic them so I haven't included a NodeIterator interface in this script. In cases where document structure changes don't affect the current / reference node, a TreeWalker can act as a surrogate for a NodeIterator because it provides all the same functionality. This is probably why NodeIterators haven't been implemented in Mozilla yet.

For more on the W3C DOM2 Traversal module, the interfaces it defines, and how to use them, consult a good DOM reference.

Script Engine / Document Object Model Required

( Javascript 1.2 | JScript 3.0 | ECMAScript 1.0 ) & DOM 1

Modification History

2003/03/14 v1.0


More about this script

Related to this script


This script is released under a Creative Commons License.