JavaScript DOM traversal

You may use this script as you wish, but without any guarantees.

This script walks a branch of the DOM starting and ending at the specified node. The parseDOMat function takes an element object and calls the walkThisBranch function which recursively traverses the DOM.

It travels down the left branch of the tree first by way of 'firstChild'. When it hits a leaf it will go to 'nextSibling' or back to 'parentNode'. It works its way back up, checking for additional child nodes and siblings as it goes. I believe this is a 'preorder traversal'.

On the way down, or when moving to siblings, it calls doStuff. Any processing to nodes that needs to be done can be done in the doStuff function. In my example, I simply construct the branch of the tree in a string. I keep up with the end tags by pushing them onto an array. Anytime I move to 'nextSibling' or 'parentNode' I pop the end tag off of the array and add it to the string, which keeps them in the proper order.

I also worked around node types Node.TEXT_NODE so they would not print. In Mozilla browsers, text nodes were showing up where there should not be text nodes. I'm not sure what causes this issue (white space, possibly?).

Alter the form data if you like, and click the button below.

Text Box 1:

Text Box 2:

Pick something:

Output will be here:

Scripts