A popular JavaScript function that has been floating around the net lately is one that can grab multiple elements from a document by name and return them in an array. It is usually referred to as "$." For example here is the $ function from the popular Prototype Library:
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; }
The function takes advantage of the "arguments" object that is available in JavaScript functions, so you can pass it as many strings as you like. The type is confirmed using the "typeof()" function and the resulting elements are pushed, stack-style, into the result array. If any of the elements are not found they will be returned as null array entries - note that you might also choose to skip null entries, or throw an error. Personally I throw errors, as I'd rather know if an element is missing.
I've been using $ quite a bit lately and came up with a more useful version that wraps the returned elements in an object instead of an array. Objects in JavaScript are basically associative arrays, so they can be used for all kinds of tasks. Since I couldn't find another cool character that I'm allowed to use, I named it "$$."
function $$() { var elements = {}; for (var i = 0; i < arguments.length; i++){ if(typeof(arguments[i]) !== 'string') continue; var element = document.getElementById(arguments[i]); elements[arguments[i]] = element; } return elements; }
This has several advantages that are tied to the features of JavaScript's Object type.
// do something with each of three textboxes. var textBoxes = $$('txt1','txt2','txt3'); textBoxes.txt1.value = 'new value.'; textBoxes['txt2'].value = 'another new value.'; textBoxes.txt3.onchange = function(){window.alert('txt3 was changed!');};
// blank out three textboxes. var textBoxes = $$('txt1','txt2','txt3'); for(var element in textBoxes) textBoxes[element].value = '';
Cool, eh? Note that this function has a subtle difference from its Array counterpart - if an argument is not a string, the "$" function will simply stick it in the array as is, while "$$" is forced to ignore it.