Here is a simple function which takes a list of id values and then grabs the relevant HTML elements from the page and returns them as an Array where you can then loop through the Array and do whatever you want with the results.
/* * @param {String}, any number of element id values can be sent to the function as a parameter * @return {Node|Array}, returns either the requested element node or an Array of element nodes */ function $() { // An empty Array which will be used to store the element nodes found var elements = []; // Loop through all the arguments for (var i=0, len=arguments.length; i<len; i++) { // Store the current argument var element = arguments[i]; if (typeof element == 'string') { // Make sure the current argument is actually a String before attempting to retrieve. element = document.getElementById(element); } if (arguments.length == 1) { // If there is only one argument then return the found element now (ending the function) return element; } // Otherwise put the current element into an Array to be returned at the end of this function elements.push(element); } return elements; }
You can now retrieve a list of elements in an Array format.
E.g.
window.onload = function() { // Set a border around the requested element. $('myElement').style.border = '1px solid green'; // You can store elements and send them to the $() function as arguments. // They will still appear in the returned Array . var element1 = document.getElementById('element1'); var element2 = document.getElementById('element2'); var elements = $( 'a', 'b', 'c', element1, element2, 'd', 'e' ); for (var i=0, len=arguments.length; i<len; i++) { alert( elements[i].firstChild.nodeValue ); } }