It’s not a terrible crime, or even a crime at all but by continually using document.getElementById, things can get a little repetitive. There are several ways with varying depth to shorten it, all relying on how much work you want to do or how often you’ll use it.
Possibly the most easiest method is to use a JavaScript library but they can add notably to your bandwidth — especially 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 $ function instead and it’ll work exactly the same.
Or if you want to make it easy to get several elements at once, try the modified Prototype $ 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 fantastic by any means but it’s a start and supports for IDs and tag names.
As a side note, Internet Explorer and Opera suffer from a getElementById bug so it may be wise to check this out before you fit all your projects with this.
Comments
No responses have been made so far. Add your comments.