A better $ function

U may remember the $ function from prototype.js and the famous Top 10 JavaScript Functions.

It was when it struck me, that the multiple arguments to the $ function returns an array, a numeric index based array. So to refer to the numeric indexes, u need to remember the order that u’d specified ur ids.

My new $ function is a little better, it returns an object with the id’s name as the member name.

function $() {
	var elements = {};
	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[arguments[i]] = element;
	return elements;

So if u use multiple ids as this…

var myObjects = $('id1', 'id2');

// Now u can use the references as 
myObjects['id1'].setAttribute("class", "myclass1");
myObjects['id2'].setAttribute("class", "myclass2");

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.