Dynamic Content using DOM methods

There are two ways to implement dynamic content in browsers.

1) Through the convenience property .innerHTML property, as shown in the previous page.
2) Through a combination of DOM methods

-Method 1

Use the convenience method  .innerHTML:

<div id="test">Old content</div>

//below code should be called after page has loaded
document.getElementById("test").innerHTML="new content"

-Method 2

Using purely DOM methods as proposed by W3C to simulate .innerHTML is a little more tricky, and for the extra work involved, may not be practical. Nevertheless, the following elegant code is devised by Rey Nunez, a surfer of JavaScript Kit and active helper on CodingForums. Using the below function, we can accomplish dynamic content in Firefox using pure DOM methods:

function dynamiccontent(elementid,content){
if (document.getElementById){
rng = document.createRange();
el = document.getElementById(elementid);
htmlFrag = rng.createContextualFragment(content);
while (el.hasChildNodes())

I won't go into detail as to how the function is constructed. Basically, document.createRange() is first used to set up a "range" over the entire document. removeChild() is then used to clear the contents of the specified element, and replaced with the new content, through appendChild(). The following demonstrates using this function to create on-the-fly HTML descriptions. Move your mouse over the links on the left:

What's New?

-In Free JavaScripts
-In JavaScript tutorials
-In Web Tutorials

The source code for each link look like this:

<a href="#" onMouseover=
"dynamiccontent('thetext',linkcontent[0])">In Free JavaScripts</a>

Where linkcontent[0] is an arbitrary variable that holds the actual HTML for the first link's description.

For the right table column that displays the HTML description, a <span> with id "thetext" is used:

<span id="thetext" style="width:100%"></span>

That's all there is to it (along with Rey's function, of course).