Skip navigation

DOM for a layer

by Ryan Frishberg
As you might guess, browser incompatibility is the cause of all the trouble for the different ways to access a layer. When NN 4 (Netscape Navigator 4) was introduced, it was the first "DHTML browser." Unfortunately, it was released before the W3C (World Wide Web Consortium) could issue recommended standards for the DOM. IE 4 (Microsoft Internet Explorer 4) uses a more advanced DOM in which every HTML element is programmable; however, it's nowhere near perfect. With the related issuance of W3C standards and the introduction of IE 5 and NN 6, DHTML is now much more powerful and standard. Authors who want their pages to be available for all viewers are left to clean up after the war.

Let's look at an example. At first, we'll be working with absolutely positioned layers; later on, we'll have a go at relative positioning.

<div id="myLayer1" style="position:absolute;top:100;left:150;z-index:3"></div>

How would each browser access this object? Let's start with the "senior" model and work our way along historically. Note that layerID stands for the ID assigned to that particular layer. In our example layer, the layerID would be "myLayer1".

Netscape 4

In NN 4, you can access a layer with:

document.layers[i] or document.layers[layerID] or document.layers.layerID or document.layerID

We'll focus on document.layers[layerID] in this tutorial. To access our example layer, the code would be: document.layers["myLayer1"].

Internet Explorer 4

With IE 4, you use:

document.all[layerID] or document.all(layerID) or document.all.layerID or layerID

We'll concentrate on the first method, but use whichever you want when you get scripting. To access our example layer, the code would be: document.all["myLayer1"].

W3C DOM (Internet Explorer 5 and Netscape 6)

Finally, there's the W3C DOM recommendation utilized by IE 5 and NN 6:

document.getElementById(layerID)

Thus: document.getElementById("myLayer1")

We can use these same methods for the neat trick of detecting which browser a viewer is using. Consider the following code:

if(document.getElementById){
      // Netscape 6 and IE 5 code goes here
}else if(document.all){
      // IE 4 code goes here
}else if(document.layers){
      //Netscape 4 code goes here
}

Backward compatible?

It's a good time to note here that IE 5 is backward-compatible, meaning that it can use both document.getElementById and document.all to access a page's elements. So, if you said:

if(document.all){
// would return IE 4 and IE 5
}

But because of our if-else() structure in our previous example to detect browsers, that won't happen, and Internet Explorer 5 users will only return true on the first if() statement. This is also a good time to note that Netscape 6 is not backward compatible, so you can't use document.layers to access an element in it.

Now, let's look at accessing the infamous CSS properties.

Next -->