Shortening document.getElementById

You must be really fed up when you need to use document.getElementById() again and again in your JS code. jQuery provides a good variant by letting you use $(el). But, if you don’t wanna use jQuery, here is a method you can use to ease out you code by simplifying document.getElementById(), document.getElementsByName(), document.getElementsByTagName() or document.getElementByClassName().

All you need to so is make a function like this.

function getId(elm){return document.getElementById(elm);}

That was it! Now, you can use just getId() instead of document.getElementById(). Exempli gratia –

getId(‘id-of-some-element’).innerHTML = ‘This is awesome!’;

^ The above code changes the innerHTML of the element to ‘This is awesome!’.

Similarly, you can make functions like getName(), getClass() or getTag() to simplify other selectors. You can even use cool function names like $(), so that it looks like $(‘id-of-some-element’), just like jQuery does it!


3 thoughts on “Shortening document.getElementById

  1. Excellent goods from you, man. I’ve have in mind your stuff previous to
    and you are just too wonderful. I actually like what you have
    received here, really like what you’re saying and the way
    wherein you assert it. You’re making it enjoyable and you still take care of to
    stay it smart. I can’t wait to read far more from you. That is actually a great site.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s