Faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

17 of 19 people (89%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I find a layer with its ID?

Jan 13th, 2001 06:47
Martin Honnen,


In NN6 and IE5+ you can simply use
  document.getElementById('layerID')
with IE4+
  document.all['layerID']
but with NN4 you have the problem that
  document.layers['layerID']
only returns top level layers so you need to write a function searching 
the document layers recursively for nested layers.
Here is the function (extended to work with NN4+, NN6 and IE4+) and 
some examples:
<HTML>
<HEAD>
<TITLE>
find layer reference from id
</TITLE>
<STYLE>
.layer {
  position: absolute;
}
</STYLE>
<SCRIPT>
function getLayer (id, document) {
  if (!document)
    document = window.document;
  if (document.layers) {
    for (var l = 0; l < document.layers.length; l++)
      if (document.layers[l].id == id)
        return document.layers[l];
    for (var l = 0; l < document.layers.length; l++) {
      var result = getLayer(id, document.layers[l].document);
      if (result)
        return result;
    }
    return null;
  }
  else if (document.all) {
    return document.all[id];
  }
  else if (document.getElementById) {
    return document.getElementById(id);
  }
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript: var l = getLayer('outerDiv'); alert(l.id + ': ' + 
l); void 0">
outerDiv
</A>
|
<A HREF="javascript: var l = getLayer('innerDiv'); alert(l.id + ': ' + 
l); void 0">
innerDiv
</A>
|
<A HREF="javascript: alert(getLayer('nonDiv')); void 0">
nonDiv
</A>
<BR>
<DIV ID="outerDiv" CLASS="layer">
<DIV ID="innerDiv" CLASS="layer">
All for Kibology.
</DIV>
</DIV>
</BODY>
</HTML>