Walking DOM Tree is Now Very Simple

Traversal of the Document Object Model (DOM) tree is often required utility by web developers. This process is now pretty easy. Learn how to walk DOM!

Traversing various data models and data structures are a very common requirement in software engineering field. Web programmers also often need to deal with the Document Object Model (DOM) of a webpage or that of an XML file. Walking DOM tree and manipulating DOM nodes is a routine deal for web developers. Therefore, since long there has been a need for a simple and easy method for accessing nodes in a DOM. Thankfully, now there is a very simple way available for traversal of DOM.

With W3C defined TreeWalker interface –now you can quickly access the required nodes. createTreeWalker() method can create an object of TreeWalker. Let’s see it by a JavaScript example:

The above code creates a tree with its root as the specified rootnode. This means you can actually get hold of any sub-tree within DOM! And in case you’re interested in working with the entire DOM you can get the complete tree by using BODY element as root. BODY element covers all the visible element on a webpage.

Caveat (as usual!): As far as I know, IE 8 (or lesser) does not support this method. Firefox/Chrome/Opera do support it. Hopefully IE 9 and above will have support for this method. You can check it out in your browser.

Isn’t that a beauty?! In the first line, you get a handle on any element by its ID and then provide this element to the createTreeWalker() method to get the full DOM tree under that element.

JavaScript is beautiful!

What’s more?! You can also specify which TYPE of nodes in the sub-tree you want to play with. NodeFilter Interface defines 15 different constants to help you in this. Of these constants, you’ll mostly use the following:

NodeFilter.SHOW_ALL (for selecting all the nodes)NodeFilter.SHOW_ELEMENT (for selecting only the text nodes)NodeFilter.SHOW_ATTRIBUTE (for selecting only the attribute nodes)NodeFilter.SHOW_TEXT (for selecting only the element nodes)

Here is an example function that will give you access to all the TEXT nodes:

Using a simple while loop, you can walk through all the nodes present in a DOM sub-tree. In the above example, sub-tree with only text nodes is returned.

Traversing DOM is often performed while developing web applications with JavaScript, Perl, Python etc. For example, the other day when I needed to randomize an HTML list, I had to grab all the LI nodes and then shuffle them. Although, in that case used another method for accessing nodes.

Lalit Kumar is the Principal Author and Founder of TechWelkin. He is a web explorer and he enjoys finding useful information on the Internet. He loves to put things together to create a bigger solution. Lalit is passionate about technology, languages and literature. You can contact Lalit via email (techwelkin [at] gmail [dot] com) or Facebook (facebook.com/techwelkin).