Question came up while working on following homework: Create 4 divs who change their color when I click on a button.
It’s all working but my teacher uses the init function for getting the divs via getElementById("div1") and I use the changeColorFunction() itself and did not use an init function at all. See below:
My solution:
function changeColor () {
document.getElementById("div1").style.background = createNewColor();
document.getElementById("div2").style.background = createNewColor();
document.getElementById("div3").style.background = createNewColor();
document.getElementById("div4").style.background = createNewColor();
}
My teachers solution:
var d1,d2,d3,d4;
function init(){
d1 = document.getElementById("d1");
d2 = document.getElementById("d2");
d3 = document.getElementById("d3");
d4 = document.getElementById("d4");
}
window.onload = init;
Its just a question about the best time/location for getting the elements.
With this little piece of code I guess not that big a difference but when DOES it matter?
When this project grows will the user ever recognize with my solution that the browser always has to get the elements first before code can run on them?
Hope you can follow.
If you are going to access those
divs many times, it may be beneficial to cache them beforehand, which is what your teacher is doing.That is, it’ll be faster to change the
styleof a cachedDOMelement, stored in variable, then to fetch it from the DOM tree, usinggetElementById, everytime you want to change its style.The difference, however, is almost negligible, but as always, the best way to see it, is to benchmark it. I’ve created a jsperf.com test case to illustrate it. You can check here the results and play with it: