Domanda

This is a piece of js code that dates back to Netscape Navigator days. I can't figure out or find the reason why this person did it this way.

function id(i)
{   

   var e;
   if (document.getElementById)
     return document.getElementById(i);
   else if (document.all)
     return document.all[i];
   else if (document.layers)
     return document.layers[i];  

   return null;
}

In newer browsers, if(document.getElementById) is always going to be true. It looks like it's checking to see if that function is there, but I'm not really sure.

The reason I'm asking, is becuase this code reads the name (not id) of elements that shouldn't have the name attribute from browsers IE8 and below. I'm tasked with trying to get it working more effectively on newer browsers. But first, I really need to understand the meaning of this code.

This reading of the name from attributes such as a <tr> is done else where and it was a pretty simple fix of using it as a custom attribute. This piece I included touches many more pieces and isn't as straightforward.

È stato utile?

Soluzione

It's a form of feature detection for getElementById - pretty much:

function id(i)
{   

   var e;
   if (document.getElementById) // the standard way
     return document.getElementById(i);
   else if (document.all) // old IE model, needed for very old IE versions
     return document.all[i];
   else if (document.layers) // old netscape model, Netscape 4 etc.
     return document.layers[i];  

   return null;
}

Unless you're supporting IE < 5.5 or Netsape < 6 , both of which you shouldn't support in all honesty - you should avoid this form of feature detection today.

This sort of code is quite common today in order to perform feature detection. I'd like to emphasize the fact that that code was best practice when it was written but is useless today. For example, today you have things like:

if ( !window.requestAnimationFrame ) {
    window.requestAnimationFrame = ( function() {
        return window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback,element) {
            window.setTimeout( callback, 1000 / 60 );
        };
} )();
}

Performing the exact same thing, only for newer APIs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top