Sign of the Dollar
September 13, 2007 9:02 pmI was perusing some JavaScript the other day and saw a strange notation that I had never seen before:
$("report")
"What is this?", I thought. It looks like Perl or PHP -- have I missed some big piece of JavaScript or is this some new feature? In a word: No.
It turns out that this is actually a function contained in the Prototype JavaScript Framework. The definition of the function is along the lines of:
-
function $() {
-
var elements = new Array();
-
for (var i = 0; i <arguments.length; i++) {
-
var element = arguments[i];
-
if (typeof element == 'string')
-
element = document.getElementById(element);
-
if (arguments.length == 1)
-
return element;
-
elements.push(element);
-
}
-
return elements;
-
}
Functionally, this is nothing special: pass in a name and get back the object. Or pass in an array and get back an array of objects. The really cool thing is the simple elegance of this method and how it cleans up your code.
-
// 'Classic' way
-
document.getElementById('userName').value = 'admin';
-
-
// Dollar way
-
$('userName').value = 'admin';
This is so simple, that it seems obvious! This saves on programmer typing, saves on page size and makes the code more readable.
In a word: beautiful.
Categories: IT, Tech
2 Comments »

