I can’t seem to define a for loop function, what am I doing wrong?
My HTML code:
<body onload="generate()">
My Javascript code:
function generate(){
for(i = 0; i < 150; i++) {
document.write("<div></div>");
}
};
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your loop is fine (other than that you don’t declare
i, and so you fall prey to the Horror of Implicit Globals), it’sdocument.writethat’s the problem. You can only usedocument.writein an inline script, not after the page has been loaded (e.g., not in thebodyloadevent). If you usedocument.writeafter the page is loaded, it tears down the page and replaces it with what you output (because there’s an implicitdocument.opencall). So in your case, your page disappears and 150 blank divs are there instead.To manipulate the page after load, you’ll want to use the DOM, references:
For instance, here’s how you’d write your
generatefunction to append 150 blank divs to the page:Or more usefully, 150 divs with their numbers in:
Live copy
Separately, if you’re going to do any significant DOM manipulation, it’s well worth using a good JavaScript browser library like jQuery, Prototype, YUI, Closure, or any of several others. These smooth over browser differences (and outright bugs), provide useful utility functions, and generally let you concentrate on what you’re actually trying to do rather than fiddling about with inconsistencies between IE and Chrome, Opera and Safari…