DOM-Tree traversal with JavaScript

Try it yourself

When you press the button, the script embedded in this page will traverse the DOM tree of the page and display it in the text field


The traversal script embedded in the page

   // Traverse this node and its children
   function traverse( node )
   {
      // Get the name of the node
      var line = node.nodeName ;

      // If it is a #TEXT node
      if( node.nodeType == 3 )
      {
         // Get the text
         var text = " " + node.nodeValue ;

         // Clean it up
         text     = text.replace( /[\r\n]/g, " " ) ;
         text     = text.replace( / +/g,     " " ) ;

         // And add it to the line
         line    += text ;
      }

      // Add the line to the text in the box
      document.getElementById( 'edit' ).value += line + "\n" ;

      // Get an array with the child nodes
      var children = node.childNodes ;

      // Traverse each of the child nodes
      for( var i = 0; i < children.length; i++ )
          traverse( children[i] ) ;
   }
  

The code behind the button

  <input type="button" value="Traverse the tree" onclick="traverse(document.documentElement)">