Javascript Shorthand for getElementById

Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that over and over.


Solution 1:

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

$( 'someID' )

Here I used $, but you can use any valid variable name.

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

byId( 'someID' )

Solution 2:

To save an extra character you could pollute the String prototype like this:

pollutePrototype(String, '绎', {
    configurable: false, // others must fail
    get: function() {
        return document.getElementById(this);
    },
    set: function(element) {
        element.id = this;
    }
});

function pollutePrototype(buildIn, name, descr) {
    var oldDescr = Object.getOwnPropertyDescriptor(buildIn.prototype, name);
    if (oldDescr && !oldDescr.configurable) {
        console.error('Unable to replace ' + buildIn.name + '.prototype.' + name + '!');
    } else {
        if (oldDescr) {
            console.warn('Replacing ' + buildIn.name + '.prototype.' + name + ' might cause unexpected behaviour.');
        }
        Object.defineProperty(buildIn.prototype, name, descr);
    }
}

It works in some browsers and you can access elements this way:

document.body.appendChild(
    'footer'.绎 = document.createElement('div')
);
'footer'.绎.textContent = 'btw nice browser :)';

I have chosen the name of the property almost randomly. If you actually wanted to use this shorthand I would suggest coming up with something easier to type.

Solution 3:

You can easily create shorthand easily yourself:

function getE(id){
   return document.getElementById(id);
}