1. Technology

JavaScript By Example

Document Object Model: 9. Walk The DOM Node By Node


Man working in an office
Image Source/Photodisc/Getty Images

Our last example looked at how to retrieve all of the nodes that are direct children of a specific node within our web page. If we start from the node for the body tag and recursively repeat the process for each node that our retrieval finds that themselves have children we can effectively step through all of the nodes that exist within the body of pur web page.

In this particular example we create a nodewalk function that will return all of the text nodes found within the node passed to it in the first parameter. The function calls itself recursively for each node that it finds which has child nodes of its own. The recursive calls make use of a second parameter to pass the array containing all of the text nodes that have already been found so that they can eventually be returned to the code that originally called the function. While any JavaScript the page uses ought to be kept in a separate file, you may have the JavaScript inline while you are initially testing it and so the script needs to ignore any text nodes that can be found inside of a script node.


<title>Example D09</title>
<script type="text/javascript" src="exampleD09.js"></script>


var node, txtnodes;
nodewalk = function(node, str) {
if (typeof str != 'array') str = [];
for (var i = 0; i   if (node[i].hasChildNodes() && 'SCRIPT' !== node[i].nodeName)
    str = nodewalk(node[i].childNodes,str);
  if (3 === node[i].nodeType)
return str;
txtnodes = nodewalk(document.getElementsByTagName('body')[0]);

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript by Example - Walk the DOM Node by Node

©2014 About.com. All rights reserved.