This section provides a tutorial example of JavaScript to show that a Web page is a tree of nodes. This shows the simplified flattened view of DOM API.
We know that a Web page, a HTML document, is a tree of elements (ignoring attributes for a moment).
From a simplified point of view, all elements are represented by the "Node" interface.
To differentiate different types of nodes from each other, we can check the "type" and "name" attributes.
Now let's walk through the tree and present each element as a node with its type and name with
a simple JavaScript example:
<html>
<!-- DOM_API_Simplified_Node_View.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>DOM API - Simplified Node View</title>
<style type="text/css">body {background-color: #aaaaff}</style>
<script type="text/javascript">
function showInterface(node, prefix, out) {
var typeName = new Array("NULL", "ELEMENT", "ATTRIBUTE", "TEXT",
"CDATA", "ENTITY_REFERENCE", "ENTITY", "RROCESSING_INSTRUCTION",
"COMMENT", "DOCUMENT", "DOCUMENT_TYPE", "DOCUMENT_FRAGMENT",
"NOTATION");
out += prefix+"[Node type="+typeName[node.nodeType]
+" name="+node.nodeName+"]\n";
var list = node.childNodes;
for (var i=0; i<list.length; i++) {
out = showInterface(list.item(i), prefix+" ", out);
}
return out;
}
function show() {
var text = document.createTextNode(showInterface(document,"",""));
var display = document.getElementById("display");
display.replaceChild(text,display.firstChild);
}
</script>
</head>
<body>
This first text is in the "body" element directly.
<p>This second text is in a "p" element.</p>
<form action="nothing" method="get">
<input type="button" value="View" onClick="show();"/>
</form>
<pre id="display">
Click the View button to see interface names...
</pre>
</body>
</html>
Notice that I am using an array to translate "node.nodeType" from an integer to a string.
In you run this JavaScript page in FireFox 2.0 and click the "View" button,
you will get a nice tree list of nodes with their types and names used in this Web page: