The Prototype Dollar

September 7th, 2008 | by jeff |

I have been slowly picking up javascript recently. I’m, well, not really impressed, but sometimes I find things I like about it. Here’s something I like; the Prototype library adds a function, the dollar function, that looks like this:

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;
}

// Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2');
function alertElements() {
  var i;
  var elements = $('a','b','c',obj1,obj2,'d','e');
  for ( i=0;i

Dustin Diaz describes it perfectly:

Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many!

Post a Comment