This section provides a tutorial example of JavaScript to show different DOM interfaces for different elements used in a Web page. This shows the object oriented view of DOM API.
We know that a Web page, a HTML document, is a tree of elements (ignoring attributes for a moment).
From an object oriented point of view, different elements are represented by different types of objects,
or interfaces in DOM term.
Now let's walk through the tree and figure out which DOM interface is supported on each element with
a simple JavaScript example:
<html>
<!-- DOM_API_Object_Oriented_View.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>DOM API - Object Oriented View</title>
<style type="text/css">body {background-color: #aaaaff}</style>
<script type="text/javascript">
function showInterface(node, prefix, out) {
out += prefix+node.constructor+"\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 a special property "node.constructor" to get the name of the constructor function name,
which is also the name of the JavaScript class that implements the DOM interface.
"node.constructor" is not valid DOM attribute.
I have tried to use the DOM attribute "node.className" to get the implementation class name. But FireFox returns
"undefined".
In you run this JavaScript page in FireFox 2.0 and click the "View" button,
you will get a nice tree list of DOM interfaces used in this Web page: