1. Computing

JavaScript By Example

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

By

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.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D09</title>
</head>
<body>
<div>x</div>
<div>y</div>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
<script type="text/javascript" src="exampleD09.js"></script>
</body>
</html>

JavaScript


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


  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Walk The DOM Node By Node

©2014 About.com. All rights reserved.