Shortening document.getElementById

It’s not a ter­rible crime, or even a crime at all but by con­tinu­ally using document.getElementById, things can get a little repet­it­ive. There are sev­eral ways with vary­ing depth to shorten it, all rely­ing on how much work you want to do or how often you’ll use it.

Pos­sibly the most easi­est method is to use a JavaS­cript lib­rary but they can add not­ably to your band­width — espe­cially if you’re just using it to shorten document.getElementById.

You could just map a short name to it:

var $ = document.getElementById;

var example = $('content');

Put simply, just use the $ func­tion instead and it’ll work exactly the same.

Or if you want to make it easy to get sev­eral ele­ments at once, try the mod­i­fied Pro­to­type $ method:

var $ = function() {
	for(var i = 0, argLength = arguments.length; i < argLength; i++)
	{
		arguments[i] = document.getElementById(arguments[i]);
	}

	return arguments;
};

var example = $('header', 'content', 'footer'); // Returns #header, #content and #footer in an array.

If you’ll be using the DOM a lot, though, it might be a good idea to write a small selector engine:

var $ = function(selector) {
	selector = selector.replace(/\s+/g, ' ').replace(/,\s?,|\s?,\s?/g, ',').replace(/^\s|\s$/g, '').split(',');
	var b = [];

	for(var i = 0, sLength = selector.length; i < sLength; i++)
	{
		var id = /^#([A-Za-z0-9-_]+)$/.exec(selector[i]);
		var tagName = /^([A-Za-z0-9-_]+)$/.exec(selector[i]);

		if(id)
		{
			selector[i] = [document.getElementById(id[1])];
		}
		else if(tagName)
		{
			selector[i] = document.getElementsByTagName(tagName[1]);
		}

		for (var j = 0, siLength = selector[i].length; j < siLength; j++)
		{
			b.push(selector[i][j]);
		}
	}

return b;
};

var example = $('#header, #content, #footer, span');

It’s not fant­astic by any means but it’s a start and sup­ports for IDs and tag names.

As a side note, Inter­net Explorer and Opera suf­fer from a getElementById bug so it may be wise to check this out before you fit all your pro­jects with this.

Comments

No responses have been made so far. Add your comments.

    What do you think? Leave a comment...