Breadcrumbs

Too Easy JavaScript - Basic DOM [6]

To learn more about the DOM and DHTML read DHTML Utopia (external link), or download the sample chapters (external link)! Learn how to create usable, slick, and interactive websites.

The Document Object Model is a powerful method for viewing a web page. JavaScript allows you to modify the DOM tree by changing elements, inserting new ones, moving elements, deleting elements, and more. DOM is the basis upon which DHTML is based, an entirely new purpose for JavaScript.

Throughout the rest of this lesson we'll use the following code to demonstrate various elements of the Document Object Model:

Code: XHTML

<ul id="list">
    <li><a href="http://www.lowter.com" id="lowter">Lowter</a></li>
    <li><a href="http://www.gizone.co.uk" id="gizone">GiZone</a></li>
</ul>

What is the DOM?

The Document Object Model (DOM) is an alternative approach towards viewing a document in a tree like structure. DOM is a standard by which scripts can alter the structure and style of a document. The Document Object Model is integrated into a variety of programming and scripting languages to give users the ability to work with XML and HTML based documents.

The Document Object Model maps out the elements (tags) in a document into a tree like structure, formed by nodes. Each element is considered an element node. Text is also considered a text node. Elements have parents, the element containing it, and children, elements within it.

Using our code from above, we can analyze how elements are related in a DOM tree. The indentions clarify the parent and child elements:

Code: XHTML

<ul id="list">
    <li>
        <a href="http://www.lowter.com" id="lowter">
            Lowter
        </a>
    </li>
    <li>
        <a href="http://www.gizone.co.uk" id="gizone">
            GiZone
        </a>
    </li>
</ul>

By separating each element into a tree like structure we are able to see how the DOM tree works. Both list option elements are children to the unordered list, who is their parent. Notice how text nodes are also treated similar to child elements, in respect that they are contained within another element.

DOM allows you to manipulate a document tree. You are able to modify, create, move, and delete elements in a tree.

Referencing Elements

Before we begin working with elements in the DOM tree, we have to establish references to them. There are a variety of methods to reference elements, but we'll focus on two core methods. getElementById() allows you to reference an element based upon its unique id, set by the XHTML id attribute. getElementsByTagName() creates references to all the elements of a specific tag.

getElementById() creates a reference for a single element based upon its unique XHTML id:

Code: JavaScript

var lowter = document.getElementById("lowter");

Now that we have created a reference to the Lowter link, we could begin to work with it in JavaScript. References are held within variables, and treated quite similar. You can change the value of a variable referencing to an element, which, in essence, is the equivalent of deleting the reference.

getElementsByTagName() is used to create a reference to all elements of a particular type:

Code: JavaScript

var all_links = document.getElementByTagName("a");

This method will always return an array, even if it only retrieves one element. From there it is treated much like an array. For example, we can derive a reference to the Lowter link from our array:

Code: JavaScript

var lowter = all_links[0];

In our code, all_links[0] is a reference to the Lowter link and all_links[1] is a reference to the GiZone link. Within our code, we could work with only one of our links by specifying the piece of data in the array, or we could work with all the links by using the array collectively.

Changing Attributes

Altering the attributes of an element allows you to change a host of an element's characteristics:

Code: JavaScript

lowter.title = "Visit Lowter.com";

The attribute that you wish to change succeeds the period after the reference. DOM also allows you to change the CSS style properties of an element:

Code: JavaScript

lowter.style.fontSize = "150%";

You access CSS properties through the style attribute. Then you access the style attribute as if it were a sub-property of the style attribute. Many CSS attributes use dashes (-) to separate multiple words. In JavaScript these properties are written in CamelCase (external link) format (commonly referred to as InterCaps). Therefore, font-size becomes fontSize.

Note: In order to access the class attribute of an element refer to it as className. This is due to the fact that class is a reserved JavaScript keyword.

Text Nodes

The Document Object Model does not consider the text within an element to be part of that element, rather a child node. In order to modify text nodes you have to "walk the DOM tree." This will be covered in detail in a later lesson, and for now you only need to know that a text node is usually the first child of an element.

Before you begin changing values you need to create a reference to the text node:

Code: JavaScript

var text_node = lowter.firstChild;

This takes our reference to the Lowter link from earlier and creates a new reference to its first child node - its text. From here we can modify its nodeValue property:

Code: JavaScript

text_node.nodeValue = "Lowter - Webmaster eZine";

The nodeValue property contains the text of the text node. We can combine these two steps into one, as a shorthand method:

Code: JavaScript

lowter.firstChild.nodeValue = "Lowter - Webmaster eZine";

Creating text nodes involves creating a new node outside of the DOM tree, eagerly awaiting to be placed within it. After you create the text node, then you append it to an element:

Code: JavaScript

var text_node = document.createTextNode("Lowter - Webmaster eZine");
lowter.appendChild(text_node);

The first line creates a new text node containing the text "Lowter - Webmaster eZine." Then the succeeding code appends the newly created text node to the Lowter link.

Creating Elements

The Document Object Model not only lets you modify elements, but create and delete them. Deleting elements will be covered in a future lesson. Creating elements involves a few steps, combining what we previously have learned in this lesson.

The process starts by creating an element. This element doesn't appear on the page, rather it exist outside of the DOM tree. Then you have the ability to change any properties and add a text node, if needed, to the newly created element. Last, you append the element as a child to another element in the DOM tree.

Code: JavaScript

var bullet_item = document.createElement("li");

var bullet_text = document.createTextNode("This bullet was added by JavaScript!");
bullet_item.appendChild(bullet_text);

var list = document.getElementById("list");
list.appendChild(bullet_item);

Preview of code

This code demonstrates the basic procedures to create a new element. Let's review over each step to clarify the exact role of each code block.

Code: JavaScript

var bullet_item = document.createElement("li");

This creates the actual element that we are starting with. You pass what tag type you would like to create as an argument to the createElement() function. Now that you've created the element, it acts identical to an element reference. For example, you have the ability to change its attributes and apply a text node.

Code: JavaScript

var bullet_text = document.createTextNode("This bullet was added by JavaScript!");
bullet_item.appendChild(bullet_text);

This code creates a new text node, containing the text - "This bullet was added by JavaScript!" The succeeding line appends the text note to the list item we previously created.

Code: JavaScript

var list = document.getElementById("list");
list.appendChild(bullet_item);

Following a similar procedure to adding text nodes, this code appends the list item to our list. First, we create a reference to our unordered list. Then we use the appendChild() function to append the list item to its newly assigned parent node.

Summary

In Part 6 of Too Easy JavaScript, you dived into the world of the Document Object Model. You learned the basics of referencing elements, changing their attributes, modifying text nodes, and adding new elements into the DOM tree. In Part 7 we will learn how to work with event handlers.