Home > JavaScript > Extending document.getElementById

Extending document.getElementById

Many newbie web developers search for a method through they can have multiple HTML element references. As we all are familiar with the popular getElementById, we also realized its limitation very early. If one need to access a number of elements for any processing together in which the HTML Elements are identified through the unique ID assigned to them either we can use the document.getElementById

multiple time or can develop a custom function that works well with multiple element IDs, which returns multiple element references.Here is one such function through which you’ll be able to get the reference of a single or multiple HTML elements. More importantly instead of using the lengthy document.getElementById throughout your code you can use a small function name.

An example of the function call can be found below

get(‘myid’); //For retrieving single element.
get([‘myid1′,’myid2’]);//For retrieving multiple elements.

The function source can be found below

function get(el) {
    if (el) {
        if (typeof el === ’string’) {
            return document.getElementById(el);
        if (typeof el === ‘object’ && el.length && el.length > 0) {
            var els = [];
            for (var i = 0; i < el.length; ++i) { 
		el[i].nodeType !== undefined ? els.push(el[i]) : els.push(document.getElementById(el[i]));
            return els;
        if (typeof el === ‘object’ && el.nodeType !== undefined) {
            return el;

As you are aware JavaScript permits the developers (us) to modify any built-in functions/objects, but I feel that it would be wise to avoid modifying the built-in functions/objects. That is the reason I’ve created the above one as a custom function that provides and extended functionality to the document.getElementById

Categories: JavaScript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: