Similar to NodeIterator, DOM Level 2 Traversal and Range module has TreeWalker interface which helps in traversing a document structure. But TreeWalker presents document elements in the tree structure view with nodes and sub-nodes instead of list like view of NodeIterator. The TreeWalker allows traversal approach to the parent node, the child node(s) and sibling nodes.

Methods of TreeWalker

createTreeWalker()

The createTreeWalker() method creates a TreeWalker object.

Syntax for createTreeWalker()

createTreeWalker (rootNode, nodeType, filterFunction, entityRefExpansion);

where,

  • root: Root node where the TreeWalker’s traversal starts
  • nodeType: Integer that specifies the types of nodes to show. It is a bitwise OR'd list of Filter specification constants from the NodeFilter DOM interface, indicating which nodes to iterate over. Some of the constants are SHOW_ALL to show all nodes, SHOW_ATTRIBUTE to show attribute nodes, etc.
  • filter: User defined filter function that can filter nodes. This function as explained earlier returns FILTER_ACCEPT, FILTER_REJECT and FILTER_SKIP to help in filtering nodes.
  • entityRefExpansion: Boolean, if true here, indicates that the contents of EntityReference nodes are visible.

firstChild()

The firstChild() method fetches the first child of the current node in the tree of given TreeWalker object and will be made the current node, if no node is found null is returned.

lastChild()

The lastChild() method fetches the last child of the current node in the tree of given TreeWalker object and will be made the current node, if no node is found null is returned.

nextNode()

The nextNode() method fetches next node in the tree represented by current TreeWalker object and will be made the current node, if no node is found null is returned.

previousNode()

The previousNode() method fetches previous node in the tree represented by current TreeWalker object and will be made the current node, if no node is found null is returned.

nextSibling()

The nextSibling() method finds next sibling node in the current TreeWalker object and will be made the current node and returns it, if no node is found it will return null.

previousSibling()

The previousSibling() method finds the previous node relative to the current node in the current TreeWalker object and be made the current node and returned, if none is found null is returned.

parentNode()

The parentNode() method finds the parent node of the current node in the given TreeWalker object and will be made the current node and returned. If current node does not have a parent node, null is returned.

Following example code demonstrates the use of TreeWalker’s node's traversal between tree nodes. Two similar methods are provided, one with only siblings alerted and one with all the elements in the tree shown.

Example of TreeWalker interface methods and properties

 

›› go to examples ››