Web DevCenter
oreilly.comSafari Books Online.Conferences.
MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA

Sponsored Developer Resources

Web Columns
Adobe GoLive
Essential JavaScript

Web Topics
All Articles
Scripting Languages

Atom 1.0 Feed RSS 1.0 Feed RSS 2.0 Feed

Learning Lab

Dynamic Content with DOM-2 (Part I of II)
Pages: 1, 2, 3


Related Reading

JavaScript: The Definitive Guide, 4th EditionJavaScript: The Definitive Guide, 4th Edition
By David Flanagan
Table of Contents
Sample Chapter
Full Description

Creating a new element node is deceptively simple. Just call the createElement method with the type of element you wish to create. It's a good idea to assign the return value of the method -- a reference to the newly created element -- to a variable if you wish to perform further operations with that element.

The following code creates a new empty paragraph element:

var newPara = document.createElement("p");

The variable newPara is now a reference to the new paragraph element.


You can create text nodes in a similar fashion, with the createTextNode method, by passing it the string of text you want in the node. As with creating elements, assigning the return value to a variable ensures that you can refer to the node later in your code.

var newText = document.createTextNode("This is a new sentence.");

The preceding code created two new nodes, but neither of them can be seen in the browser because they have not been inserted into the document. Newly created nodes float freely in the JavaScript until you assign them to a parent object or to the document body.

Every object that inherits the node interface has a method called appendChild, which allows that node to have other nodes inserted into it. For example, you can insert the new text node newText into the new paragraph element newPara using the appendChild method:

var newPara = document.createElement("p");
var newText = document.createTextNode("This is a new sentence.");

Now all you need to do is insert the paragraph element into the document body. To do this, you need a reference to the BODY element of the document. There are several ways to get this reference. Most newer browsers (IE5 and NS6) allow you to use document.body, e.g. document.body.appendChild(newPara);,but this is a non-standard convenience property which may not work in future versions.

A more standards-compliant way is to use the document object's getElementsByTagName method to get a reference to the first BODY element found in the document.

var bodyRef = document.getElementsByTagName("body").item(0);

The item(0) method is necessary because getElementsByTagName returns a collection of elements it finds with the specified tag name. Since there is usually only one BODY tag in an HTML page, you use the item method to get the first item in the collection.

Another standards-compliant way to reference the document body is to use the getElementById method. This assumes, however, that you have bothered to assign an ID attribute to the <BODY> tag of your HTML page.

<body id="docBody">
var bodyRef = document.getElementById("docBody");

You can also use getElementsByTagName and getElementById to obtain references to page objects other than the body. For example, clicking this link will invoke a script that uses getElementById to get a reference this very paragraph element (which has been given an ID attribute of "example1"). The script then inserts a new text node into this element with the appendChild method.

The code used to do this is as follows:

<script type="text/javascript">
    function insertNewText()
    var newText = document.createTextNode(" DOM methods are cool, are they not?");
    var para = document.getElementById("example1");

Since a paragraph element with an ID of "example1" already resides within the BODY of the document, there is no need to reference the body at all. This is a simple example, but the concepts demonstrated could be used to achieve some complicated DOM manipulations.

There are some restrictions imposed on the creation of new nodes. One to consider is that a newly created node can only be inserted in the document that created it. This means that if you're using a series of frames, you cannot create an element in one frame and append it into the document body of another frame. Its also not possible to pass an element from one window to another.

It's also worth noting that you are restricted to the logical hierarchy of the document and the types of nodes you are manipulating. You may get errors if you try things like inserting a node into itself, into one of its own children, or into another node that does not allow children of that type.

Whither innerHTML?

You may be wondering why it's worth using these seemingly complex, overlong JavaScript statements to create a single bit of text or an HTML element when you could use innerHTML and be done with it.

innerHTML was a convenience property introduced by Microsoft as a means of reading and writing the HTML content of an element. For example, you could easily create a multi-celled table structure and insert it into your page with innerHTML:

var str = '<table border="1">';
str += '<tr><td>Cell One</td><td>Cell Two</td><td>Cell Three</td></tr>';
str += '</table>';
document.all["paragraphOne"].innerHTML = str;

innerHTML was incorporated into the Mozilla codebase and is now a part of NS6. So why not use it? The primary reason is that innerHTML does not return any references to the nodes it creates. If at some point you needed to change the text inside the second TD element of this new table, you would have to somehow find a reference to that second cell--something you would already have if you had used createElement(), which always returns a node reference. You could use document.all or even document.getElementById() to retrieve a reference, but that assumes that you have properly assigned unique IDs to each element in your string. At that point, it's easier to simply rewrite the entire string and reinsert in into paragraphOne.

Ultimately, the approach you choose depends on what you intend to accomplish. If you are simply displaying text or HTML and have no need to access the new elements being created, use innerHTML. If, however, you plan on manipulating specific items within a larger dynamically generated structure, take the extra time to construct it with DOM document methods.

Pages: 1, 2, 3

Next Pagearrow