Jamex Jamex - 2 months ago 6
Javascript Question

javascript window.onload event correct usage

I have this loop code to reduce the DOM calls in my javascript, and reuse them.

aarr = [];

for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}


I have been shown that if the code is ran before the DOM is complete, then the array is null. Moving the script after the last html code will work.

So now I want to put this code inside the
window.onload
event so to not have to move the script code to the bottom of the page. But it apparently does not work because it appears that the array loop is executed before the DOM is completed.

window.onload=function(){

var aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
}


Also, I have tried to remove the "var" to remove scope without making a difference.

Answer

You could also try this approach without using a framework:

window.onload = (function(){
    return function(){
        var aarr = [];
        for (var z=1; z<=10; z++) {
            aarr.push(document.getElementById("a"+z));
               alert(aarr[z-1].id);
        }
     };
})();

JSFiddle