« Part 1 | Part 3 »

Part 2 - What is the DOM and how to manipulate it using Javascript

The Document Object Model (DOM) is a tree structure representing an HTML page.  Let’s review a sample of HTML code and it’s corresponding DOM tree.

Sample HTML code:

<div id="sample">

This is a <b>sample of HTML</b> <br> to demonstrate the DOM
</div>



Here is the corresponding DOM structure

In our example, the DIV tag is the root element, as it contains all other tags and text. The DIV element has two objects associated with it, attributes which references all attributes of a tag (element) and childNodes which references everything else (tags and text contained).

It’s important to understand that text is considered an element as well - any text that is not contained within a child element, is considered an element (for example, “this is a” is an element).

So how can we access the DOM using Javascript? both IE and Firefox support the getElementById DOM function:

var elm=document.getElementById("sample");	//get a reference to the DIV element

The getElementById function locates an element using it’s id attribute (in our case, the DIV element’s id was “sample"). Make sure you have an id attribute in elements you are interested in accessing via Javascript.


Now let’s access the DOM:

alert(elm.attributes.id.value);		//will alert "sample"
alert(elm.childNodes[0].nodeType);	//will alert 3 - TEXT NODE
alert(elm.childNodes[0].nodeValue);	//will alert "this is a"
alert(elm.childNodes[1].nodeType);	//will alert 1 - ELEMENT NODE
alert(elm.childNodes[1].nodeValue);	//will alert null - element nodes don't have a value
alert(elm.childNodes[1].childNodes[0].nodeValue);	//will alert "sample of HTML"
elm.childNodes[0].nodeValue="What a ";	//changes the content of the TEXT element to "What a "



We can also access the content of an element as text:

var elm=document.getElementById("sample");
alert(elm.innerHTML);		//will alert "This is a <b>sample of HTML</b> <br> to demonstrate the DOM"
elm.innerHTML+=" <br>let's move on";




innerHTML gives us direct text-level access to everything contained in an element. We can replace or append content and the DOM will be rebuilt on the fly. Here’s what the DOM looks like after the above code has been executed: