|
Something
Old, Something New (cont)
Notice
that I'm using the <DIV>
tag's style attribute to define its style properties, rather than
an inline or stylesheet reference in the page header. There's
a very important reason for this, which I'll discuss later in this
article.
If
the preceding <DIV>
tag were part of a DHTML application, you might have referenced
it using the following JavaScript code:
In
Netscape:
var myElement = document.layers["sampleDiv"];
In
Internet Explorer:
var myElement
= document.all["sampleDiv"];
These approaches won't work in NS6. Use the document's getElementById
method instead:
var myElement
= document.getElementById("sampleDiv");
The
second document method, getElementsByTagName,
returns a collection of all elements of a specific type. For example,
if you wanted to access all <DIV>
tags, you could simply use this:
var allDivs =
document.getElementsByTagName("div");
The
allDivs variable
would then contain an array of references to all the <DIV>
elements in the document. Each individual <DIV>
element could then be individually accessed through its ordinal
position (allDivs[0],
allDivs[1] and so
on).
Each
individual element also implements the getElementsByTagName
method, which lets you retrieve references to nested child elements
within block elements. For example, to retrieve a collection of references
to all nested <DIV>s
within the sample layer tag, you could use:
var myElement
= document.getElementById("sampleDiv");
var allDivs = myElement.getElementsByTagName("div");
|
IE
compatibility note:
Fortunately, Microsoft built support for getElementById
and getElementsByTagName
into IE version 5 and up, so the preceding
code works in both Netscape and IE.
|
Incidentally,
developers who long for the bad old days can use getElementsByTagName
to create their own document.all
collection of sorts (this trick only works in NS6 and Mozilla):
var all = document.getElementsByTagName("*");
Now
that you have a consistent way to reference <DIV>
elements, I'll show
you the different ways to manipulate them via JavaScript.
|