Rough Guide to the DOM

Welcome to the Rough Guide To The DOM.

In two parts, this series introduces the Document Object Model, explaining its benefits, and exploring its implementation.

Rough Guide To The DOM – Part 1

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.

Rough Guide To The DOM – Part 2

Now that you know the theory behind the new DOM, it’s time to take off the gloves and get your hands dirty.

In this article, find out how the new rules apply to old favourites like image swaps, form validation and frame navigation, and then learn how to use ordinary JavaScript to add and remove elements from the document tree on the fly.

Rough Guide To The DOM – Part 1

The Current State Of Denmark

In Shakespeare’s "Hamlet", one of the characters famously remarks, "Something’s rotten in the state of Denmark". And each time I sit down to code some dHTML, I’m assailed by a sense of wonder at his perspicuity. That comment, laden with an undertone of doom, is such a perfect appraisal of the numerous incompatibilities between the two major browsers, and the problems they cause for developers on a daily basis, that it’s hard not to laugh. And I would… if I wasn’t already weeping buckets.

These incompatibilities are particularly glaring in an area known as the DOM, or Document Object Model, a standard method of accessing each and every element in the document, together with its attributes. When a primitive version of the DOM was first introduced, developers immediately realized how useful it could be in adding new levels of interactivity to a static Web page. However, as the two major browsers branched out in different directions, developing DOM constructs that were mutually incompatible, that elation quickly turned to disappointment – after all, no developer likes writing different versions of the same script for different browsers.

Of course, all is not lost. Efforts have been under way, most noticeably at the W3C to establish common standards for all browsers. The release of the CSS specification, and then of the DOM Level 0 and Level 1 specifications, has resulted in most of the major browsers falling in line with the proposed standards. The flip side: since a standard is now available, browser makers will soon stop supporting their previous DOM versions… which means that all the code you wrote and the clever workarounds you devised will no longer work in newer versions of the browsers.

You can already see this happening – code written specifically for Netscape 4.x no longer works in Netscape 6.x, which is built on the Mozilla engine – and so, every developer needs to understand the new DOM standard and its impact on dHTML code development.

Over the next few pages, I’ll be illustrating some of the new DOM constructs, together with examples of how they can be used in "real" HTML documents. My trusty steed in this journey will be Mozilla, the wonderful open-source browser available at, which claims to be the most standards-compatible browser currently available.

Before we start, a few disclaimers.

One, this tutorial is not meant to be an exhaustive reference to the DOM – you can buy a book for that. It is merely a guide to help you in making the transition to the new object model.

Second, I don’t claim to be an expert on the DOM, and much of the material in this tutorial is based on my own experience as a developer.

Finally, as new DOM standards are proposed and disposed, the material here may become invalid; you should always refer to the most current standard or recommendation at for up-to-date information (this is one of my favourite documents – I use it frequently when I have trouble sleeping).

With the formalities out of the way, let’s get started.

Back To Basics

We’ll start with the basics – a very simple HTML page.

<html>   <head></head>   <body bgcolor="white">   <div id="a" style="font-family: Arial; color: white;    background: black">Wassup?</div>   </body>   </html>

Let’s alter the font colour of the text within the <div>. In Internet Explorer, this would typically be accomplished with

<script language="JavaScript"> = "red";   </script>

Here’s the code I would use in Mozilla:

<script language="JavaScript">   var obj = document.childNodes[0].childNodes[1].childNodes[0]; = "red";   </script>

An explanation is in order here. Under the new DOM, every element in an HTML document is part of a "tree", and you can access each and every element by navigating through the tree "branches" until you reach the corresponding "node". Given that, here’s my representation of the HTML document above, in "tree" form.

document   | -- <html>   | -- <head>   | -- <body>   | -- <div>

Now, to get to the <div>, I need to:

  1. start at the top ("document");
  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 in the document tree. A quick way of verifying this is to use an alert() on the object

<script language="JavaScript">   var obj = document.childNodes[0].childNodes[1].childNodes[0];   alert(obj.nodeName); = "red";   </script>

which displays the name of the tag – DIV – in an alert box.

At this point, I can begin futzing with object attributes – in the example above, I’ve altered the "color" style attribute. Don’t worry about this for the moment; simply verify that you have understood the manner in which I navigated through the document tree to reach the DIV.

Copyright Melonfire, 2000. All rights reserved.

Navigating The Family Tree

In addition to the various childNodes[], the DOM also offers a number of other objects/properties which can simplify navigation between document elements.

  • firstChild – a reference to the first child node in the collection
  • lastChild – a reference to the last child node in the collection
  • parentNode – a reference to the node one level up in the tree
  • nextSibling – a reference to the next node in the current collection
  • previousSibling – a reference to the previous node in the current collection

And so, with reference to the example above, I could use any of the alternative routes below to navigate to the <div> tag.

document.childNodes[0].childNodes[1].firstChild    document.childNodes[0].firstChild.nextSibling.firstChild    document.childNodes[0].childNodes[1].firstChild.firstChild.parentNode

Each child in the tree can be either an HTML tag or a "text node". This brings up an important point – blank spaces and carriage returns between the various tags can affect the document tree structure, creating text nodes in the tree structure and causing much gnashing of teeth as you adjust your code to the new tree.

What’s In A Name?

It’s precisely for this reason that the DOM offers a faster and more efficient method of accessing elements within the page – the getElementById() method.

I’ve rewritten the example above to demonstrate how this method can be used.

<script language="JavaScript">    var obj = document.getElementById("a"); = "red";    </script>

As you can see, this is much simpler to read… and code.

Every node has some basic properties which come in handy for the developer – for example, the "nodeName" property returns the tag name, while the "nodeType" property returns a number indicating the type of node (HTML tag=1; HTML tag attribute=2; text block=3). If the node happens to be a text node rather than a tag, the "data" and "nodeValue" properties return the text string.

The following example demonstrates how the various node properties can be accessed – uncomment the various alert() method calls to display the various object properties.

<html>    <head></head>    <body id="body" bgcolor="white"><font face="Arial"     size="2">This stuff is giving me a headache already!</font>    <script language="JavaScript">   

// get to the <font> tag    var fontObj = document.getElementById("body").childNodes[0];   

// check the tag - returns "FONT"    // alert(fontObj.nodeName);    // check the type of node - returns 1    // alert(fontObj.nodeType);    // get the text within the <font> tag    var textObj = fontObj.childNodes[0];    // check the text value - returns "This stuff is giving     me a headache already!"    // alert(;    // check the type of node - returns 3    // alert(textObj.nodeType);    </script>    </body>    </html>

And incidentally – a text node which contains no data returns the value "#text" to the "nodeName" property – try replacing the line of text from within the <font> tags above with a couple of blank spaces to see what I mean.

Ducks In A Row

In addition to the getElementById() method, which is typically used to obtain a reference to a specific element, the DOM also offers the getElementsByTagName() method, used to return a collection of a specific type of element. For example, the code


would return a collection, or array, containing references to all the <form> tags in the document. Each of these references is a node, and can then be manipulated using the standard DOM methods and properties.

Consider the following document, which contains three <div>s, each containing a line of text

<html>    <head>    </head>    <body bgcolor="white">    <div id="huey">    Huey here!    </div>    <div id="dewey">    Dewey in the house!    </div>    <div id="louie">    Yo dude! How's it hangin'?    </div>    </body>    </html>

and then study the code I’d use to manipulate the text within the second <div>

<script language="JavaScript">   

// get a list of all <div> tags    var divCollection = document.getElementsByTagName("div");   

// get a reference to the second <div> in the collection    var deweyObj = divCollection[1];   

// verify that we are where we think we are    // alert(deweyObj.getAttribute("id"));    // change the text string within the <div>    deweyObj.childNodes[0].data = "Dewey rocks!";    </script>

A collection of all the tags within a document (a lot like "document.all") can be obtained with


Copyright Melonfire, 2000. All rights reserved.

Changing Things Around

Now that you know how to find your way to specific HTML elements in the document, it’s time to learn how to manipulate them. Since most of this manipulation involves altering tag attributes on the fly, the DOM offers the getAttribute() and setAttribute() methods, which are designed expressly for this purpose.

Consider the following modification to the example you just saw, which uses these two methods to alter the font size and the text string.

<html>     <head></head>     <body id="body" bgcolor="white"><font face="Arial"      size="2">This stuff is giving me a headache already!</font>     <br>     Click to <a href="javascript:increaseFontSize();">increase font size</a>      or <a href="javascript:changeText()">change text string</a>    

<script language="JavaScript">    

// get to the <font> tag     var fontObj = document.getElementById("body").childNodes[0];    

// check the tag - returns "FONT"     // alert(fontObj.nodeName);     // check the type of node - returns 1     // alert(fontObj.nodeType);     // get the text within the <font> tag     var textObj = fontObj.childNodes[0];    

// check the text value - returns "This stuff is giving      me a headache already!"     // alert(;     // check the type of node - returs 3     // alert(textObj.nodeType);     function changeText()     {    

// alter the node value = "I need some aspirin. Now.";     }     function increaseFontSize()     {    

// get the value of the "size" attribute of the node     var size = fontObj.getAttribute("size");    

// increase by 1     size += 1;    

// set the new value     fontObj.setAttribute("size", size);     }     </script>     </body>     </html>

I’ve used two different methods here. In order to alter the font size, I’ve first used the getAttribute() method to return the current value of the attribute, and then used the setAttribute() method to write a new value. However, altering the text string is simply a matter of changing the value of the text node’s "data" property.

There are a couple of things to keep in mind when using getAttribute() and setAttribute(). All attribute names should be lowercase, and both names and values should be enclosed in quotes (if you omit the quotes, the values will be treated as variables). Obviously, you should only use attributes which are relevant to the tag under consideration – for example, you cannot use a setAttribute("src") on a <font> tag.


An alternative way of obtaining (and setting) attribute values is via the attributes[] collection, which is essentially an array containing a list of all the attribute-value pairs for a specific tag. I’ve modified the previous example to illustrate how this works – uncomment the various alert()s to see the values of the different properties.

<html>     <head></head>     <body id="body" bgcolor="white">     <font face="Arial" size="2">This stuff is giving me      a headache already!</font>    

<script language="JavaScript">    

// get to the <font> tag     var fontObj = document.getElementById("body").childNodes[0];    

// return the number of attributes of the <font> tag     // or the length of the attributes[] collection     // returns 2     // alert(fontObj.attributes.length);     // returns the name of the first attribute - "face"     // alert(fontObj.attributes[0].name);     // returns the value of the first attribute - "Arial"     // alert(fontObj.attributes[0].value);     // changes the value of the first attribute to "Verdana"     fontObj.attributes[0].value = "Verdana";    

// returns the new value of the first attribute - "Verdana"     // alert(fontObj.attributes[0].value);     </script>     </body>     </html>

Copyright Melonfire, 2000. All rights reserved.


The DOM also allows you to modify CSS properties of specific HTML tags – as the following example demonstrates:

<html>      <head>      <script language="JavaScript">      function disappear()      {      var obj = document.getElementById("mirage"); = "none";      }      </script>      </head>      <body>      <div id="mirage">      Now you see it...      </div>      <a href="javascript:disappear()"> you don't!</a>      </body>      </html>

I’ve done something similar in the very first example in this article – take a look at that one too, while you’re at it.

Using this technique, it’s possible to apply almost any inline style to an element on the page. Remember that style properties which are hyphenated – for example, "background-color" and "font-family" – need to be written as a single word with the first character after the hyphen capitalized – for example, "backgroundColor" and "fontFamily". The next example should illustrate this clearly:

<html>      <head>      <script language="JavaScript">      function transform()      {      var obj = document.getElementById("marvel"); = "Verdana"; = "40pt"; = "red"; = "black"; = "underline"; = "center"; = "10";      }      </script>      </head>      <body>      <div id="marvel">      Captain Marvel      </div>      <a href="javascript:transform()">shazam!</a>      </body>      </html>

That’s about it for the moment. In the second part of this article, I’ll be running through some simple code examples for simple JavaScript applications – image swaps, form validation and frame navigation – using the new DOM structures. I’ll also be discussing the appendChild() and createNode() functions, which allow developers to add new elements to the document tree through program code. Don’t miss it!

Note: All examples in this article have been tested on Mozilla (build 18). Examples are illustrative only, and are not meant for a production environment. YMMV!
Copyright Melonfire, 2000. All rights reserved.

Rough Guide To The DOM – Part 2

Digging Deeper

In the first part of this article, I took you through the basics of navigating an HTML document via the DOM, and explained the various methods and collections available to you. If you understood all that (and I hope you did), you should now have a pretty clear idea of how to manipulate a typical HTML document, and change interface elements on the fly.

Over the next few pages, I’m going to dig a little deeper into the DOM, with illustrations of how the DOM interfaces with tables, forms, images and frames. I’ll also be discussing some of the methods available to add (and modify) nodes to the DOM tree through JavaScript, and point you to some of the Web’s better resources on the subject.

Let’s get cracking!

Making The Swap()

The first item on the agenda today is an illustration of how you can use the DOM to accomplish one of the most popular dHTML applications – the image swap. Take a gander at the following HTML document:

<html>       <head>       </head>      


<a href="" onMouseOver="javascript:imageSwap();"       onMouseOut="javascript:imageSwap();"><img id="logo" src="logo_n.gif"       width=50 height=50 border=0></a>      

</body>       </html>

Now, I’ve set this up so that "mouseover" and "mouseout" events on the image are handled by the JavaScript function imageSwap(). This function is responsible for swapping the image each time an event occurs – so let’s take a look at it.

<script language="JavaScript">       var normal = "logo_n.gif";       var hover = "logo_h.gif";      

function imageSwap()       {       var imageObj = document.getElementById("logo");       var imageSrc = imageObj.getAttribute("src");      

if (imageSrc == normal)           {           imageObj.setAttribute("src", hover);           }         else           {           imageObj.setAttribute("src", normal);           }       }       </script>

If you remember what I taught you last time, none of this should come as a surprise. I’ve first defined the "normal" and "hover" state images, and then created a function called imageSwap(), which is called whenever the mouse moves over and out of the image.

The imageSwap() function obtains a reference to the image via its ID, and then obtains the current value of the image’s "src" attribute. It then checks the value against the values of the "normal" and "hover" variables, and changes the image source appropriately.

Turning The Tables

Next up, tables. Take a look at the following HTML document, which contains a table with two rows, three cells each.

<html><head></head><body><table border="1" cellspacing="5"       cellpadding="5"><tr><td>R1, C1</td><td>R1, C2</td><td>R1,       C3</td></tr><tr><td>R2, C1</td><td>R2, C2</td><td id="r2c3">R2,       C3</td></tr></table></body></html>

Now, when navigating through a table, there’s one important point to be aware of – from the DOM vie, a table must be treated as though it included an additional <tbody> tag immediately after the <table> tag and before the <tr> tags. Adding this to the equation, the page above now looks like this:

<html><head></head><body><table border="1" cellspacing="5"       cellpadding="5"><tbody><tr><td>R1, C1</td><td>R1, C2</td><td>R1,       C3</td></tr><tr><td>R2, C1</td><td>R2, C2</td><td id="r2c3">R2,       C3</td></tr></tbody></table></body></html>

The usual DOM navigation rules now apply, as the following example demonstrates. This script drills down to the last cell of the second row and alters both the background colour of the cell and the text string within it.

<script language="JavaScript">      

// get to the cell       // you could also use        // var cellObj =       document.childNodes[0].childNodes[1].childNodes[0].childNodes[0].       childNodes[1].childNodes[2];      

var cellObj = document.getElementById("r2c3");      

// get to the text within the cell       var cellTextObj = cellObj.childNodes[0];      

// set background colour       cellObj.setAttribute("bgcolor", "red");      

// and text = "Second row, third column";       </script>

Copyright Melonfire, 2000. All rights reserved.


Another very popular use of JavaScript is form validation – verifying the data entered into an online form. In the next example, I’ll be using the DOM and some simple JavaScript to ensure that the checkbox is ticked and the email address entered into the text field is in the correct format. Here’s the form:

<html>        <head>        </head>       


<form action="somescript.cgi" method="post"         onSubmit="return check();">        Email address:        <br>        <input id="email" type="text" name="email" size="30">        <br>        <input id="spam_me" type="Checkbox" name="spam_me">Yes, I         want you to send me megabytes of useless advertisements via         email. I love buying crummy products from people who         probably flunked kindergarten.        <br>        <input type="submit">        </form>       

</body>        </html>

And here’s the validation script:

<script language="JavaScript">       

function checkEmail()        {       

// get to the field        var obj = document.getElementById("email");       

// value of field        var str = obj.value;       

// define pattern to match email address        var pattern =        /^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+        (.[a-zA-Z0-9_-]+)+/;       

// match the string to the pattern        var flag = pattern.test(str);       

if(!flag)          {          alert ("Please enter a valid email address");          return false;          }          else          {          return true;          }       

}        function checkSpam()        {        // get to the field        var obj = document.getElementById("spam_me");       

// checkbox ticked?          if (obj.checked)          {          return true;          }          else          {          alert ("Please check the box");          return false;          }        }       

function check()        {        // perform validation and submit form if all is well          if(checkEmail() && checkSpam())          {          return true;          }          else          {          return false;          }        }       


As you can see, the form is submitted only after receiving a positive (true) result from the JavaScript function check(). This function, in turn, calls the functions checkEmail() and checkSpam(),which first obtain references to their respective form elements and then check their values for validity.

Copyright Melonfire, 2000. All rights reserved.

In The Frame

It’s also interesting to see how the DOM works with frames. Consider the following example, which sets up two frames, "left.html" and "right.html".

<html>         <head>         </head>        

<frameset  cols="20%,*">             <frame name="left" src="left.html" scrolling="auto"              frameborder="no">             <frame name="right" src="right.html"  scrolling="auto"              frameborder="no">         </frameset>        


In order to illustrate how to navigate across frames, I’m going to write a simple script which changes the background colour of the right frame when the appropriate link is clicked in the left frame. Here’s the right frame,

<html>         <head>         </head>        

<body id="body">         </body>         </html>

and here’s the left frame – note how each link calls the changeFrameBackground() function with a color as parameter.

<html>         <head>         </head>        


<a href="javascript:changeFrameBackground('red')">Red</a>         <br>         <a href="javascript:changeFrameBackground('blue')">Blue</a>         <br>         <a href="javascript:changeFrameBackground('green')">Green</a>         <br>         <a href="javascript:changeFrameBackground('black')">Black</a>        

</body>         </html>

Finally, let’s take a look at the function which does all the work.

         <script language="JavaScript">        

var bodyObj = top.right.document.getElementById("body");        

function changeFrameBackground(col)         {         bodyObj.setAttribute("bgcolor", col);         }        


Since this is a frameset, it’s necessary to prefix the document.getElementById() method call with a reference to the appropriate frame. This prefix is necessary to identify to the DOM which frame is being called, and to obtain a reference to the correct document tree.

Once a reference to the right frame’s <body> tag is obtained, changing the frame’s background colour is a simple setAttribute() away.

Branching Out

The DOM also comes with a bunch of built-in methods designed to manipulate the DOM tree, adding and removing nodes from it on the fly. As you’ve already seen, a node on the DOM tree could be either an HTML tag or a text fragment – and the DOM comes with methods to add both these types of nodes to the tree, through program code.

I’ll begin with the createElement() method, which is used to create a new HTML tag. The following code snippet creates an <img> tag as a node, and assigns it the name "imageObj".

<script language="JavaScript">         var imageObj = document.createElement("img");         </script>

Once the node has been created, attributes can be assigned to it using the setAttribute() method. For example, the code snippet

<script language="JavaScript">         imageObj.setAttribute("src", "logo_n.gif");         imageObj.setAttribute("width", "50");         imageObj.setAttribute("height", "50");         </script>

is equivalent to the tag

<img src="logo_n.gif" width="50" height="50">

Once the node has been created, the next order of business is to add it to the document tree – a task accomplished by the appendChild() method. The appendChild() method is used to append the newly-created node to a specific location in the tree.

The following code snippet would attach the "imageObj" node as a child of the element identified by "heading1".

<script language="JavaScript">         document.getElementById("heading1").appendChild(imageObj);         </script>

Copyright Melonfire, 2000. All rights reserved.

Dumbing It Down

Just as you can create HTML tags as nodes, the DOM also allows you to create new text nodes on the tree with the aptly-named createTextNode() method. Here’s an example:

          <script language="JavaScript">          var insultObj = document.createTextNode("Could you *be* any dumber?");          </script>

Again, the appendChild() method comes into play to attach the new text node to the appropriate branch of the document tree.

<script language="JavaScript">          document.getElementById("heading1").appendChild(insultObj);          </script>

Let’s see how this plays out in a real-life example. I’ve put together a simple HTML page, which contains nothing except a set of <p> tags and some JavaScript code. The JavaScript will create a new text node and a new <img> tag and add them to the document tree as children of the <p> tag, using the code snippets I’ve just demonstrated.

<html>          <head>          </head>         


<p id="heading1"></p>         

<script language="JavaScript">         

// set up the image          var imageObj = document.createElement("img");          imageObj.setAttribute("src", "logo.gif");           imageObj.setAttribute("width", "50");           imageObj.setAttribute("height", "50");           document.getElementById("heading1").appendChild(imageObj);         

// set up the text node          var insultObj = document.createTextNode("Could you *be* any dumber");          document.getElementById("heading1").appendChild(insultObj);         

// use this for testing          var pObj = document.getElementById("heading1");         

// returns IMG          // alert (pObj.childNodes[0].nodeName);         

// returns #text          // alert (pObj.childNodes[1].nodeName);         


</body>          </html>

Although the page contains only a single <p> tag, running the script will add an <img> tag and a line of text to the document tree, which will be immediately visible in the browser.

Of course, the DOM comes with a bunch of other methods as well – here’s a brief list, together with an explanation of their function.

  • removeNode() – remove a node (and/or all its children) from the document tree
  • replaceNode() – replace a node with another node
  • cloneNode() – duplicate an existing node
  • swapNode() – swap the positions of two nodes in the document tree
  • insertBefore() – insert a node at a specific point in the document tree

Most of these are self-explanatory, and they’re not used all that often, so I don’t plan to discuss them in detail – they’re included here for the sake of completeness.


Should you be interested in learning more about the DOM, there are a number of resources available to you online. Here’s a brief list:

The official W3C DOM specifications, at developer resources, at and

DOM sample code at

An interesting article on transitioning from proprietary DOMs to the W3C standard, at

A structural (logical) view of the DOM, at Rough Guide to the DOM

An XML introduction to the DOM, at

And, before I go, a final comment. While the new DOM may appear to be far less flexible and easy to use than the proprietary models developers have been used to, the fact remains that it offers one very important advantage: standardization. This DOM has been written in such a manner that every element on a page is finally available to the developer via standard navigation rules, and can be manipulated using standard object methods and properties.

In the short run, it may be difficult – even frustrating – to re-code Web pages as per the new DOM; however, I believe that the effort is well worth putting in, as it immediately ensures that your pages will be viewable across all standards-compliant browsers. It should be noted that much of the confusion in the past (and the resulting profusion of proprietary DOM interfaces) was due to the lack of clear direction from the W3C; now that a DOM specification has been finalized and released, future versions of all the major browsers should support it completely, and we should hopefully see an end to browser incompatibilities that have plagued developers in the past.

Here’s hoping!

Note: All examples in this article have been tested on Mozilla (build 18). Examples are illustrative only, and are not meant for a production environment. YMMV!
Copyright Melonfire, 2000. All rights reserved.


Category: javascript Time: 2002-09-18 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.190 (s). 12 q(s)