0

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>");
    }
};
2
  • What output are you expecting, and what output are you getting? Commented Nov 24, 2011 at 12:54
  • Why do you think it's not working? Have you used Firebug in Firefox to look at your page after the fact, to see if the divs are there? They will all be empty so they won't be visible on the page, except as white space. At any rate your code works. Commented Nov 24, 2011 at 12:55

4 Answers 4

11

Your loop is fine (other than that you don't declare i, and so you fall prey to the Horror of Implicit Globals), it's document.write that's the problem. You can only use document.write in an inline script, not after the page has been loaded (e.g., not in the body load event). If you use document.write after the page is loaded, it tears down the page and replaces it with what you output (because there's an implicit document.open call). 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 generate function to append 150 blank divs to the page:

function generate() {
    var i;

    for (i = 0; i < 150; i++){
        document.body.appendChild(document.createElement('div'));
    }
}

Or more usefully, 150 divs with their numbers in:

function generate() {
    var i, div;

    for (i = 0; i < 150; i++){
        div = document.createElement('div');
        div.innerHTML = "I'm div #" + i;
        document.body.appendChild(div);
    }
}

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I'm thinking of making a simple roguelike to learn Javascript, so I try to do it without relying on any libraries.
@Leventhan: I'm not sure what a "roguelike" is, but good luck! The things to learn are: JavaScript itself, and then the things you can do with it in your target environemnt(s). In the browser, that means using the DOM (or a library that does that for you). The DOM is an API to the browser, not part of JavaScript itself. If you're doing browser work, it's definitely good to have some idea of how the DOM works, even if you do end up (later) using a library that abstracts some of the hassles away for you.
0

The document.write mentioned in https://stackoverflow.com/q/8257414/295783 is the reason it does not work. The first document.write wipes the page including the script that is executing. A better way is

<html>
<head>
<script type="text/javascript">
  var max = 150;
  window.onload=function() {
    var div, container = document.createElement('div');
    for (var i=0;i<max;i++) {
      div = document.createElement('div');
      container.appendChild(div);
    }
    document.body.appendChind(container);
  }
</script>
</head>
<body>
</body>
</html>

Comments

0
window.addEventListener("DOMContentLoaded", function() {

    for(var i = 0; i < 150; i++) {

        document.body.appendChild( document.createElement("div") );

    }

}, false);

This should work, didn't test it though. It's important to wait for the 'DOMContenLoaded' event, because else some elements might not exist at the time your script was executed.

Comments

0

do the folowing;

function generate(){
    var echo="";
    for(i = 0; i < 150; i++){
        echo+="<div></div>";
    }
    document.getElementById("someID").innerHTML=echo;
    //document.write(echo); //only do this, if you want to replace the ENTIRE DOM structure
};

2 Comments

In what world do we have innerContent?
you are correct. Its innerHTML of course. I was thinking about innerText/textContent, so that no script would be executed. But in this case, innerHTML is the way to go. I corrected my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.