The Netlobo logo - a Nevada desert landscape

Using Javascript to get an Element by ID

A cross-browser alternative to the javascript getElementById function

Published Jul 26, 2005 by lobo235
Last updated on Aug 27, 2007

Recently I was writing a bit of Javascript for one of my sites when I came across a new way to get html elements using their id. I'm not talking about the getElementById function because it only works with DOM capable browsers. The method I came up with will work for older browsers as well as newer ones supporting getElementById. Most web designers and developers want their pages to be cross-browser compatible. When you are dealing with things in the realms of CSS or Javascript though, this can often times be hard to achieve.

Older versions of many browsers do not use getElementById to access elements on a page using their id. Instead they use document.all or document.layers to do this. The Javascript function I wrote is basically a wrapper function that checks to see which method the current browser uses to find elements using their id and then it uses that method and returns the result. Using this Javascript function, you can make many pieces of Javascript code you find on the web be cross-browser compatible. Without further adieu, here is the function:

function returnObjById( id )
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}

Simple and sweet, the function performs well and helps you achieve a degree of cross-browser compatibility you didn't have before. As always, I am open to your feedback regarding this Javascript function. Please let me know if you have any suggestions or improvements.

15 comments for this article.

del.icio.us logo add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
The Javascript Select-box onchange Problem
Javascript Number Formatting
Unobtrusive Javascript made easy