Programmer's Guide > Programming and Scripting Techniques > Basic Document Manipulation Using the DOM and AOM > Traversing a Document Using the DOM and AOM > Traversing and Printing a Document Structure
  
Traversing and Printing a Document Structure
In this example, as the document is traversed, the tag name and up to the first 60 characters of each node are printed to illustrate the hierarchical structure of the current document.
In addition to demonstrating how to walk a DOM tree, this example also shows how to access the names of nodes (Node.nodeName), how to determine a node's type (Node.nodeType = text, element, comment, or processing instruction), and how to extract text content from a document (Node.data).
function printTree(n, elem) {
if (elem == null) {
if (n == 0)
print("document has no element nodes");
return;
}
var str = "";
for (var i = 0; i < n; i++)
str += " ";
// show this node
print(str + elem.tagName + getAttrs(elem));
str += " ";
// followed by its children
for (var child = elem.firstChild; child != null;
child = child.nextSibling) {
if (child.nodeType == child.ELEMENT_NODE)
printTree(n + 1, child);
else if (child.nodeType == child.TEXT_NODE) {
// for text nodes, show the first 60 characters
// note, concatentation with a null string is used to convert
// the Java String returned into a JavaScript string.
var text = child.data + "";
if (text.length > 60)
print(str + '"' + text.substr(0, 60) + "...\"");
else
print(str + '"' + text + '"');
}
else if (child.nodeType == child.COMMENT_NODE) {
var text = "#comment: " + child.data;
if (text.length > 60)
text = text.substr(0, 60) + "...";
print(str + text);
}
else if (child.nodeType == child.PROCESSING_INSTRUCTION_NODE)
print(str + "#pi: " + child.target + ' ' + child.data);
else // all others
print(str + child.nodeName);
}
}
// start at the root
printTree(0, Application.activeDocument.documentElement);