Tags:

Create an alias to document getelementbyid in JavaScript

Thursday, March 24, 2011 EDT

by: Eric Potvin

Tags: javascript

document.getElementById is pretty useful when developing Web 2.0 websites. But, writing over and over "document.getElementById" can be annoying. There is a simple way to fix that problem.

Creating an alias is a good way to simplify your code.

<script language="JavaScript" type="text/javascript">
this.$ = function(elem) {
    if(typeof(elem) != "string") {
        return false;
    }
    if(!document.getElementById(elem)) {
        return false;
    }
    return document.getElementById(elem);
}
</script>
Now, if you want to reference a HTML tag using the ID, you simply need to use the $
$('info');
instead of:
document.getElementById('info');
Happy JavaScripting!

Last comment by: Philipp Hagemeister

comments (2) Comments Feeds
Share this article:
This can be greatly simplified by just assigning document.getElementById to the variable you want it to, even better, using jQuery (note that $ is already used by jQuery, so this code will likely confuse many JavaScript snippets and libraries).
Comment by Philipp Hagemeister Saturday, September 3, 2011 EDT
0
I agree a variable is easy to create, but if you use custom function you will have to declare this variable globally in order to use it everywhere. Which is kind of not really what we need here. jQuery is good but you don't need to include the library if you use only one feature.
Comment by Eric Saturday, September 3, 2011 EDT
1

Add a comment

* If your comment require a response from us, please make sure you leave your email

Captcha

* is required
The posting of advertisements, profanity, or personal attacks is prohibited.
Please review our terms of use

Latest Articles

Top Articles

Category List

Top of the page
Loading, please wait ...