ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

How to traverse the DOM Tree with Javascript

Jeffrey P. Bigham

Related Ads

To make dynamic pages it is often quite useful to be able to traverse the DOM tree of the current HTML document. This interface allows you to update individual branches and leaves and restructure the page however you like. Below is a simpel recursive function that will visit every node in the tree and shows how to determine that you've reached a leaf node.

The code is called with the traverseDomTree() function, which finds the body element and then calls the recursive version of the function, which keeps track of the curr_element and the level of the tree that the code has reached. In customizing this, not all of this functionality will be required.


function traverseDomTree() {
  var body_element = document.getElementsByTagName("body").item(0);
  traverseDomTree_recurse(body_element, 0);
  alert("The end"); 
}

function traverseDomTree_recurse(curr_element, level) {
  var i;
  if(curr_element.childNodes.length <= 0) {
    // This is a leaf node.
    if(curr_element.nodeName == "#text") {
      // This is a text leaf node,
      // with the following text.
      var node_text = curr_element.data;
     }
  } else {
    // Expand each of the children of this node.
    for(i=0; curr_element.childNodes.item(i); i++) {
      traverseDomTree_recurse(curr_element.childNodes.item(i), level+1);
    }
  }
}

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles