Yes, it repeats in order to use the same function with and through each time with a different argument:
var myImage = document.getElementById("myImage"); var myDiv = document.getElementById("myDiv");
So, a good thing would be a function that takes all these arguments at once:
function getElementsByIds(/* id1, id2, id3, ... */) { var elements = {}; for (var i = 0; i < arguments.length; i++) { elements[arguments[i]] = document.getElementById(arguments[i]); } return elements; }
Then you will have links to all your items stored in one object:
var el = getElementsByIds("myImage", "myDiv"); el.myImage.src = "test.gif";
But you still have to list all of these identifiers.
You can simplify it even if you need all elements with identifiers:
function getElementsWithIds() { var elements = {}; var elementList = document.querySelectorAll("[id]"); for (var i = 0; i < elementList.length; i++) { elements[elementList[i].id] = elementList[i]; } return elements; }
But it would be quite expensive to call this function if you have many elements.
So, theoretically, if you were to use the with keyword, you could write code like this:
with (getElementsByIds('myButton', 'myImage', 'myTextbox')) { myButton.onclick = function() { myImage.src = myTextbox.value; }; }
But I do not want to advertise using with . There is probably a better way to do this.
Robert Feb 17 '12 at 22:06 2012-02-17 22:06
source share