JS: How to make document.getElementById cross browser?

document.getElementById doesn't seem to work in all browsers (I mean some old ones), and I'm sure there are developers who don't know this.

What solutions do you propose to make cross browser?

thanks

+6
source share
4 answers

If document.getElementById does not work, then either:

  • You are doing it wrong (invalid HTML trying to access names instead of identifiers, etc.)

or

  • You are working with Netscape 4.x and Internet Explorer 4.x

There are three ways to work with browsers of this era.

  • Let people know update. They are not verifiable, nightmares with security protection for the user and the author.
  • Create material that works , and make sure your JS checks for getElementById and friends before trying to use them ( if (!document.getElementById) { return false; /* Insufficient DOM to bother with JS here */ } )
  • Learn about document.all and document.layers
+9
source

Are you sure this is not this kind of problem ? Look at this interestingly, I did not know this before.

However, to complement what was already suggested by David Dorward, you write a function like the one below.

 function getElement (id) { if (document.getElementById) { return document.getElementById(id); } else if (document.all) { return window.document.all[id]; } else if (document.layers) { return window.document.layers[id]; } } 
+4
source
 getElemID(obj){ if(document.getElementByID){ return document.getElementByID(obj); } else if (document.all){ return document.all[obj]; } else if (document.layers){ return document.layers[obj]; } else { alert("Could not find support"); return false; } } 
+1
source
 function getDOM() { if (document.getElementById) { return document.getElementById; } var window_document = window.document || {}; var elements = window_document.all || window_document.layers; if(elements) { return function(x) { return elements[x]; } } // everything failed throw new InternalError('No means to "getElementById"'); } 

... then

 var getElementById; try { getElementById = getDOM(); } catch(err) { alert(err); } // implicit 0K var oHTMLElement = getElementById('#main'); 
0
source

All Articles