< Previous PageNext Page > Hide TOC

Using the Document Object Model From JavaScript

The JavaScript Document Object Model implements the Document Object Model (DOM) specification, developed by the World Wide Web Consortium. This specification provides a platform and language-neutral interface that allows programs and scripts to dynamically access and change the content, structure and style of a document —usually HTML or XML—by providing a structured set of objects that correspond to the document’s elements.

The Level 2 DOM specification in particular added the ability to create object trees from style sheets, and manipulate the style data of document elements.

The Document Object Model is already implemented in a wide variety of languages, most notably JavaScript. Each declaration in the JavaScript DOM was created using the Interface Definition Language (IDL) files from the W3C.

By taking advantage of the DOM, you can:

Contents:

Accessing a Document’s Structure with the DOM
Using the Document Object Model
Other Resources


Accessing a Document’s Structure with the DOM

The primary function of the Document Object Model is to view, access, and change the structure of an HTML document separate from the content contained within it. You can access certain HTML elements based on their id identifier, or allocate arrays of elements by their tag or CSS class type. All transformations are done according to the most recent HTML specification. More importantly, they happen dynamically—any transformation will happen without reloading the page.

The DOM tree is completely comprised of JavaScript objects. Some of the fundamental and most commonly-used ones are listed in Table 1.

Table 1  Commonly used JavaScript DOM types

DOM object

Definition

document

Returns the document object for the page. Represents the root node of the DOM tree, and actions on it will affect the entirety of the page.

element

Represents an instance of most structures and sub-structures in the DOM tree. For example, a text block can be an element, and so can the entire body section of an HTML document.

nodeList

A nodeList is equivalent to an array, but it is an array specific to storing elements. You can access items in a nodeList through common syntax like myList[n], where n is an integer.

There are a number of JavaScript methods specified by the DOM which allow you to access its structure. Some of the fundamental and most commonly-used ones are listed in Table 2.

Table 2  Commonly used JavaScript DOM methods

DOM method

Parent class(es)

Definition

element getElementById(id)

document, element

Returns the element uniquely identified by its id identifier.

nodeList getElementsByTagName(name)

document, element

Returns a nodeList of any elements that have a given tag (such as p or div), specified by name.

element createElement(type)

element

Creates an element with the type specified by type (such as p or div)

void appendChild(node)

element, node

Appends the node specified by node onto the receiving node or element.

string style

element

Returns the style rules associated with an element, in string form. You can also use this to set the style rules, by calling something like div.style.margin = "10px";

string innerHTML

element

Returns the HTML that contains the current element and all the content within it. You can also use this to set the innerHTML of an element, by using something like element.innerHTML = "<p>test</p>";

void setAttribute(name, value)

element

Adds (or changes) an attribute of the receiving element, such as its id or align attribute.

string getAttribute(name)

element

Returns the value of the element attribute specified by name.

The entire DOM reference can be found in “Other Resources.”

Using the Document Object Model

This section introduces some code examples to familiarize you with the Document Object Model.

To work with DOM code examples, you need to create a sample HTML file. The code below represents the HTML file you will use in the following examples:

<HTML>
<HEAD>
    <TITLE>My Sample HTML file</TITLE>
</HEAD>
<BODY>
 <DIV id="allMyParas" style="border-top: 1px #000 solid;">
    <P id="firstParagraph">
        This is my first paragraph.
    </P>
    <P id="secondParagraph">
        This is my second paragraph.
    </P>
 </DIV>
</BODY>
</HTML>

Now that you have an HTML document to work with, you’re ready to do some DOM transformations. This first example appends a paragraph to the DOM tree, following the firstParagraph and secondParagraph elements:

parasDiv = document.getElementById("allMyParas");
thirdPara = document.createElement("p");
thirdPara.setAttribute("id", "thirdParagraph");
parasDiv.appendChild(thirdPara);

Of course, the paragraph has no text in it right now. Using the DOM, you can even add text to that new paragraph:

thirdPara.innerHTML = "This is my third paragraph.";

You may also want to add a bottom margin to the enclosing div element, where there is currently only a top margin. You could do that with setAttribute, but you would have to copy the existing style attribute with getAttribute, append to it, and then send it back using setAttribute. Instead, use the style block:

parasDiv.style.borderBottom = "1px #000 solid";

Finally, maybe you want to change the style on all the paragraph elements within the enclosing div element. You can use the nodeList-generating getElementsByTagName method to get an array of the paragraph elements, and then cycle through them. In this example, we’ll add a gray background to all the paragraphs:

parasInDiv = parasDiv.getElementsByTagName("p");
for(var i = 0; i < parasInDiv.length; i++) {
    parasInDiv[i].style.backgroundColor = "lightgrey";
}

The combination of the JavaScript Document Object Model with WebKit-based applications or Dashboard widgets is powerful. By tying these scripts to mouse events or button clicks, for example, you can create very dynamic and fluid content on your web page or within your WebKit-based applications, including Dashboard widgets.

Other Resources

The following resources will help you use the JavaScript Document Object Model:



< Previous PageNext Page > Hide TOC


© 2004, 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.