rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Create an alias to document getelementbyid in 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.

this.$ = function(elem) {
    if(typeof(elem) != "string") {
        return false;
    }
    if(!document.getElementById(elem)) {
        return false;
    }
    return document.getElementById(elem);
}

Now, if you want to reference an HTML tag using the ID, you simply need to use the $

$('info');

instead of:

document.getElementById('info');