Skip navigation

Out with the Old, in with the New

by Ryan Frishberg
Now that we've practiced manipulating layers and accessing their CSS properties, we'll discuss writing new content in a layer. As with most DHTML effects, it is a misconception to that that this is difficult. Let's examine browser by browser how to rewrite a layer's content.

Netscape 4

First up is NN4. This is the most familiar, using ordinary (and archaic) JavaScript.

document.layers[layerID].document.open();
document.layers[layerID].document.write('This is the New Content');
document.layers[layerID].document.close()


But, with the with() function, we can shorten it into:

with(document.layers[layerID].document){
      open();
      write('This is the New Content');
      close();
}

That wasn't so tough. It's like writing content onto a page with document.write().

Internet Explorer 4

Now, let's look at how IE4 rewrites content:

document.all[layerID].innerHTML="This is the New Content";

Along with innerHTML, IE supports outerHTML, innerText, and outerText. To show you the difference, we'll use an example layer and alert() each of these properties to ya'. Here's our example layer (Note that this will not work in NS 4 or totally in NS 6).

<div id="myLayer1" style="position:absolute;visibility:hidden">This is <b>the Layer's</b> Content</div>

That just shows you the difference between all 4 of those properties. Notice that innerText and outerText return the same thing. However, there is a big difference between them. If you set innerText, it replaces the text inside the layer (the innerText of the layer), but if you set outerText, it replaces the whole layer (the outside of the layer) so that it doesn't exist anymore. For the most part, we'll just use innerHTML.

IE 5 and NS 6

IE 5 can use innerHTML, outerHTML, innerText, and outerText just like IE 4 can, but NS 6 only supports innerHTML. I'll explain about NS 6 in the W3C DOM part of this tutorial, but for now, we'll just use innerHTML. So, in IE 5 and NS 6, we're going to use:

document.getElementById(layerID).innerHTML="This is the New Content";

Wonder Function

Earlier, we wrote a generic function to access a layer's CSS properties. Now let's write a function to write new content in the layer:

<script>
      function writeLayer(layerID,txt){
            if(document.getElementById){
                  document.getElementById(layerID).innerHTML=txt;
            }else if(document.all){
                  document.all[layerID].innerHTML=txt;
            }else if(document.layers){
                  with(document.layers[layerID].document){
                        open();
                        write(txt);
                        close();
                  }
            }
      }
</script>

We can use this function to create the typing text script found in the introduction of this tutorial.

Next -->