Traversing a Document's Nodes
Using the JavaScript bindings, it is fairly trivial to navigate through a document's nodes, as demonstrated in the following example.
Example: Navigating and Reporting a Document's Object Model
This example navigates through a document's nodes and returns the document's DOM.
SourceThis example uses the document example from earlier in this article with scripting necessary to navigate the DOM:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>DOM Walk and Display</title>
<style type="text/css">
div.div1 { background-color: #999999; }
div.div2 { background-color: #BBBBBB; }
table, table * { border: thin solid black; }
table { border-collapse: collapse; }
td { padding: 5px; }
</style>
<script type="text/JavaScript">
var s = new String();
// Add node's children to the listing (String s)
function showChildren(node,lvl) {
// Only track elements (1), text (3), and the document (9)
if ( node.nodeType == 1 || node.nodeType == 3 ||
node.nodeType == 9 ) {
// Add dashes to represent node level
for (var x = 0; x < lvl; x++) { s = s + "--"; }
// Report first 20 chars for text nodes
if ( node.nodeType == 3 ) {
mynodeType = node.nodeValue;
if (mynodeType.length > 20) {
mynodeType = mynodeType.slice(0,16) + "...";
}
} else {
// Report "Element/Tag" for elements
mynodeType = "Element/Tag";
}
s = s + "+ " + node.nodeName + " (" + mynodeType + ")\n";
// If the node has children, let's report those too
if ( node.hasChildNodes() ) {
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
showChildren(children[i],lvl+1);
}
}
}
}
function domwalk() {
// Navigate through the DOM and report it in another window
alert("Click OK to display the document's DOM");
showChildren(document,0);
displaywin = window.open("","displaywin",
"width=400,height=400,scrollbars=yes,resizable=yes");
displaywin.document.write("<pre>"+s+"</pre>");
}
</script>
</head>
<body onload="domwalk()">
<div class="div1">
<h1>Heading 1</h1>
<table>
<tr><td>Cell 1</td><td>Cell 2</td></tr>
<tr><td>Cell 3</td><td>Cell 4</td></tr>
</table>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam <b>nonummy nibh euismod</b> tincidunt ut laoreet
dolore magna aliquam erat volutpat. Ut wisi enim ad minim
veniam, quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat.</p>
</div>
<div class="div2">
<h1>Heading 2</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut laoreet
dolore magna aliquam erat volutpat. Ut wisi enim ad minim
veniam, quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat.</p>
<ol id="sortme">An ordered list
<li>Gamma</li>
<li>Alpha</li>
<li>Beta</li>
</ol>
</div>
</body>
</html>
This code works by recursively calling the showChildren() function for each node that has children in the document (identified by the hasChildNodes() property). The nodes are added to a global string (s) until the end of the document is reached (there are no more nodes or children). The script then spawns a new window to display the full DOM as recorded in the string. (Note that your user agent must allow pop-up windows for this code to work.)
The script displays the windows shown in Figure 3. The DOM is displayed with representative levels (dashes and pluses) in the new window.
Figure 3
Next Time
This article introduced the W3C Document Object Model and the JavaScript properties and methods you can use to traverse it. You can also use the values and types properties of nodes to effectively search the DOM for nodes, as well as modify node contents, properties and even order in the document. The next article in this series will demonstrate how to find a particular node.
This article is adapted from Web Standards Programmer's Reference: HTML, CSS, JavaScript, Perl, Python, and PHP by Steven M. Schafer (Wrox, 2005, ISBN: 0-7645-8820-6), from Chapter 21 "The Document Object Model." This is the first of a three-part series of articles on this topic. Steve programs in several languages and technologies, with extensive experience in Linux and related open-source platforms.
