Thursday 3 April 2014

Shorthand for getElementById in Javascript 2

Some times I feel lazy to use document.getElementById('selector_id') when I'm working with plain Javascript.

I can hear You also feel the same. Lets we can create our own shorthand for getElementById().

All we need is to just write a function for that.

var $ = function (id) {
    return document.getElementById(id);
};

Here after We can call our get our element by ID like this,
$('btn')

I think you want to see it in DEMO... You can find it below...

NOTE : Most of the javascript libraries are using dollar sign ($) as short hand. So, you can use any character or word instead of '$' as a shorthand.


2 comments: