HomeDHTML Page 2 - Rough Guide To The DOM (part 1)
Back To Basics - DHTML
It's the bane of Web developers everywhere - conflicting standards, browser incompatibilities, and code that changes every time a new browser version hits the Web. But fear not - charging in on a white steed comes a heroic knight, clad in the attire of the new W3C DOM and armed with the tools to make this nightmare end forever. Read on to find out how the new DOM finally brings some standards to the decidedly non-standard world of the Web.
<script language="JavaScript">
var obj = document.childNodes[0].childNodes[1].childNodes[0];
obj.style.color = "red";
</script>
An explanation is in order here. Under the new DOM, every element in anHTML document is part of a "tree", and you can access each and everyelement by navigating through the tree "branches" until you reach thecorresponding "node". Given that, here's my representation of the HTMLdocument above, in "tree" form.
2. move down to the main branch - the <html> tag, or"document.childNodes[0]";
3. then to the second sub-branch - the <body> tag or"document.childNodes[0].childNodes[1]";
4. then to the <div> - "document.childNodes[0].childNodes[1].childNodes[0]";
At this point, I have successfully navigated my way to the <div> element inthe document tree. A quick way of verifying this is to use an alert() onthe object
which displays the name of the tag - DIV - in an alert box.
At this point, I can begin futzing with object attributes - in the exampleabove, I've altered the "color" style attribute. Don't worry about this forthe moment; simply verify that you have understood the manner in which Inavigated through the document tree to reach the DIV.