Entry
How can I find the number of layers in a document using the DOM. NS6 doesn't support document.layers.length
Jan 23rd, 2001 08:43
Ian Grant, X X,
Since the new DOM doesn't support the document.all object nor the
document.layers object, you are given the document.getElementsByTagName
() and document.getElementById() object methods instead. Netscape 4's
layers object gives you exactly how many layers there are through
document.layers.length, whether you use the <LAYER> tag, the <SPAN>
tag, or the <DIV> tag, or all three. Unfortunately, in your case
neither Internet Explorer nor Netscape 6 support the layers object.
Let's examine what is happening in each browser when you use their
typical methods of accessing their respective DOMs:
document.layers.myDiv
document.layers['myDiv']
document.layers[0]
document.layers0
Might be synonymous in Navigator 4. What you are accessing is an
object array of layers elements, which is why you get the number of
layers with document.layers.length.
document.all.myDiv
document.all['myDiv']
document.all[14]
myDiv
Might also be synonymous in Explorer 4+. Once again you are accessing
an array of elements, but not necessarily of <DIV>s and <SPAN>s.
Rather, you are accessing every page element through the object
array 'document.all'.
document.getElementById('myDiv')
document.getElementsByTagName('DIV')[0]
Might be synonymous in Netscape 6. As in the previous examples, you
are accessing an array, however getElementById() retrieves the page
element for you by its ID, and getElementsByTagName() produces an array
of whatever tag name you give it. (By the way, these two methods will
also work in Explorer 5.)
To determine how many layers (or in this case <DIV>s or <SPAN>s) there
are, simply assign document.getElementsByTagName to an object and
extract its length or simply do it all in one line of code:
var obj = document.getElementsByTagName('div');
alert(obj.length);
// or in one line
alert(document.getElementsByTagName('div').length);
Keep in mind that if you use both <DIV>s and <SPAN>s in your code,
you'll have to check for both separately.
I hope this helps you.
Ian Grant
idgrant@pandi.20m.com