Javascript Reference
Categories: TreeWalker

javascript TreeWalker Description

@March 15, 2008, 1:22 a.m.
TreeWalkerFirefox/Netscape/NN 7 IE n/a Chrome/Safari/DOM 2  

  

The TreeWalker object is a live, hierarchical list of nodes that meet criteria defined by the document.createTreeWalker( ) method. The list assumes the same parent-descendant hierarchy for its items as the nodes to which its items point. The createTreeWalker( ) method describes the node where the list begins and which nodes (or classes of nodes) are exempt from the list by way of filtering.

 

The TreeWalker object maintains a kind of pointer inside the list (so that your scripts don't have to). Methods of this object let scripts access the next or previous node (or sibling, child, or parent node) in the list, while moving the pointer in the direction indicated by the method you chose. If scripts modify the document tree after the TreeWalker is created, changes to the document tree are automatically reflected in the sequence of nodes in the TreeWalker.

 

While fully usable in an HTML document, the TreeWalker can be even more valuable in an XML data document. For example, the W3C DOM does not provide a quick way to access all elements that have a particular attribute name (something that the XPATH standard can do easily on the server). But you can define a TreeWalker to point only to nodes that have the desired attribute, and quickly access those nodes sequentially (i.e., without having to script more laborious looping through all nodes in search of the desired elements). As an example, the following filter function allows only those nodes that contain the author attribute to be a member of a TreeWalker object:

function authorAttrFilter(node) {
    if (node.hasAttribute("author")) {
        return NodeFilter.FILTER_ACCEPT;		
    }
    return NodeFilter.FILTER_SKIP;
}
 

A reference to this function becomes one of the parameters to a createTreeWalker( ) method that also limits the list to element nodes:

var authorsOnly = document.createTreeWalker(document, 
NodeFilter.SHOW_ELEMENT, authorAttrFilter, false);
 

You can then invoke TreeWalker object methods to obtain a reference to one of the nodes in the list. When you invoke the method, the TreeWalker object applies the filter to candidates relative to the current poistion of the internal pointer in the direction indicated by the method. The next document tree node to meet the method and filter criteria is returned. Once you have that node reference, you can access any DOM node property or method to work with the node, independent of the items in the TreeWalker list.

 
Object Model Reference
 
TreeWalkerReference
 
Object-Specific Properties
 
currentNodeexpandEntityReferencefilterrootwhatToShow
 
Object-Specific Methods
 
firstChild( )lastChild( )nextNode( )nextSibling( )
parentNode( )previousNode( )previousSibling( )
 
Object-Specific Event Handler Properties

None.


Powered by Linode.