Web Design Company Portfolio

Now the #1 Directory for Website Designers on Google!

Manipulating the Document Object Model using Javascript

by Andrew Charles 04-19-2006
In the beginning there was only darkness. The Internet was a place of flat unlinked text. Then it was said, let there be layout engines, and there were layout engines. We created pages upon pages of HTML. We put the world's information into tables and we center-justified it. When we looked at what we had created, we saw that it was good... But there was something missing.

HTML is boring. It is static to the point of stagnating. Dynamic pages are all the rage, and updating pages client-side instead of server-side is what the new Web is all about. But how do we go about creating the new Web? Javascript provides an answer, with functions to edit the HTML that makes up a page, but that's awkward at best. This is where the Document Object Model, or DOM, comes in.

The DOM is a way of conceptualizing the page. Think of it as a tree, with all the components of your page as branches. If you had a tree and wanted to prune one of its branches, you certainly wouldn't cut down the tree and begin re-growing it without the branch, but this is exactly what you're doing when you send a page back to the server for every update. DOM gives you the methods you need to access and change individual components in your webpage.

To begin, we should look at what a basic DOM tree looks like. Take this HTML code for example:
<html>
<head>
<title>My Page</title>
</head>
<body id="body">
<h2 id="header">Hello</h2>
<div id="content">World</div>
</body>
</html>
The DOM tree for this page looks like this:
document
 -HTML
  -HEAD
   -TITLE
    -'My Page'
  -BODY
   -H2
    -Hello
   -DIV
    -World
The first step in working with the DOM is learning how to access the individual branches. The easiest, and by far the most popular, method is using the function document.getElementById(). Using this function, we can use Javascript to grab a reference to a branch by using the ID specified in HTML. For example, in order to get a reference to our H2 branch in the example above, we would use this code:
var element = document.getElementById('header');
What can we do now that we have the reference? Anything we want. We can change the HTML contents of the element by modifying its innerHTML property:
element.innerHTML = 'Universe';
We can set its CSS class by modifying the className property:
element.className = 'headerClass';
We can put the browser's focus on it by calling its focus() method:
element.focus();
We can even find it's position and dimensions on the page by accessing its offset properties:
width = element.offsetWidth;
height = element.offsetHeight;
posX = element.offsetLeft;
posY = element.offsetTop;
Changing an element is an incredibly useful ability, but if you want to fundamentally change the DOM tree? For example, what if you want to remove an element from the page entirely? Well to do that, you need to have a bit more understanding of the DOM elements as Objects. Each element of your page is an object. Each object is referenced by another object, its parent object, up to the top level Document Object. Its important to keep in mind how all these objects are linked. If you want to remove an element, you can't just delete it, you have to remove the reference to it from its parent object. If you were allowed to just delete an element, you'd be left with an invalid pointer in its parent object. This creates an orphaned parent node. Think of it as deleting a webpage without removing the links to that page from other sites.

What does this all mean? It means that in order to delete a branch, or node, from the DOM, you have to instruct its parent object to remove it. You do this using the javascript removeChild() function. So, in our example above, if we wanted to remove the H2 element, we could do something like this:

header = document.getElementById('header');
body = document.getElementById('body');
body.removeChild(header);
Simple enough, right? But what if we don't know the parent object of the element we want to delete? Well, lucky for us, each object also contains a reference to its parent object, accessible through its parentNode property. So, an alternative way to delete our h2 element would be:
header = document.getElementById('header');
body = header.parentNode;
body.removeChild(header);
Great, so now we can delete elements from a page. What if we want to add an element? We can do this through Javascript too! Let's say we wanted to add a new element after our content div in the example page? To do this, we'd first have to create our new element using the function document.createElement(). The createElement function takes one parameter, the name of the tag you want to create. For example, if we wanted to create a new span element, we'd use the following code:
var new_span = document.createElement('span');
We now have a new element, but it has not yet been placed into the DOM tree. To do this, we use the function appendChild on the DOM node we want to insert into:
body = document.getElementById('body');
body.appendChild(new_span);
And that's it, we now have a new span inserted at the bottom of the body. If we wanted to place text inside our new element, we'd need to create a text node and append it to our object. This can be accomplished using the document.createTextNode function. This function takes a parameter of the initial text to set in the node:
var text = document.createTextNode("How ya doing?");
new_span.appendChild(text);
It's that simple! With these tools, you are well on your way to creating your own dynamic web applications. There's plenty more manipulations you can perform on the DOM tree, including replacing nodes, copying nodes, and changing node attributes. A good reference is the W3C DOM specification (http://www.w3.org/TR/DOM-Level-2-Core/) where you can explore all the properties and methods available to you.