jJavascript window.onload event correct usage
27,767
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);
}
};
})();
Author by
Jamex
Updated on July 14, 2022Comments
-
Jamex almost 2 years
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.
-
Jamex over 12 yearsThanks Rick, I am not using jquery, so this won't work for me.
-
Jamex over 12 yearsThanks, I read that post before and I actually am getting this to work for firefox with that code, unfortunately, IE versions are all giving me errors. I am walking through the script line by line.
-
Jamex over 12 yearsThanks Erwin, are these jquery code? I don't know/have jquery.
-
Richard A over 12 yearsHey jamex.i made some changes to ur loop and it works fine for me..see the fiddle added :)
-
Jamex over 12 yearsThanks Richard, I will give it a try.
-
Codebeat over 12 yearsThe second code is the non-jQuery version, the getObj function
-
Codebeat over 12 yearsbelow the line "Or without a framework (native javascript):" is yours
-
Saxoier over 12 years@Richard Aikoroje: Next time fork the fiddle. In addition:
(function(){})();
is useless. The only thing you achieve is that you expand the[[scope]]
.