Proper DOM

Using DOM methods to create html

There are a few ways to create HTML on the client using javascript, my prefered way is to use the proper DOM methods, as show below.

Concider the following HTML:

<div class="holder"><span>This</span> is the HTML</div>

The following script will create some identical HTML to the example above.

   // define vars for the references to the elements
   var elDiv;
   var elSpan;

   // create the div element 
   elDiv = document.createElement("div");
   // set the CSS class
   elDiv.className = "holder";

   // create the span element
   elSpan = document.createElement("span");
   // create the textNode for the span
   tnSpan = document.createTextNode("This");
   // append the textNode to the span
   elSpan.appendChild(tnSpan);
   
   // append the span to the div element
   elDiv.appendChild( elSpan )
   // create and append the last of the text
   elDiv.appendChild( document.createTextNode(" is the HTML") );
   
   // append the div element to the body of the document
   document.body.appendChild(elDiv);

Click here to try it for your self

You will see that it continues to append element to the page each time you click.

There were alot of steps in that example; it could have be reduced to a more concise piece of code.

Using these Methods you can keep a reference to the elements you have created, this means that you no longer need to search the DOM to locate the element.

Note: "class" is a reserved word in javascript so you have to use className to change the CSS class of an element.

Last Updated : 11/01/2006 @ 14:11