SummerBoy
SummerBoy

Reputation: 125

Why doesn't my for loop execute?

When i use document.write it works, but it doesn't work with getElementById. The same for while. `

<div id="mydiv"></div>
    <script>
        var i = 0;
        for (i=0; i<=10; i++){
        //while (i<=10){
            document.getElementById("mydiv").innerHTML = i + "<br>";
            //i++;
        }
    </script>

Output is just 10, but I want to list 0-10 line by line. How to fix?

Upvotes: -1

Views: 56

Answers (4)

Alexandre Khoury
Alexandre Khoury

Reputation: 4022

While other answers are true, I think it's a risky practice because your browser might try to execute the code before having loaded all html elements. (For example if your div is after the code..)

So I propose this:

<div id="mydiv">
<script>
    for (var i=0; i<=10; i++){
        document.write ( i + "<br />");
    }
</script>
</div>

N.B: However, keep in mind you cannot use "document.write" after the page finished loading.

You can also do that to be safe:

<div id="mydiv"></div>
<script>
    document.onload = function(){
        temp=""
        for (var i=0; i<=10; i++){
            temp += i + "<br />";
        }
        document.getElementById("mydiv").innerHTML = temp;
    }
</script>

Upvotes: 0

Jeremy Gordon
Jeremy Gordon

Reputation: 551

You're overwriting. Append instead.

for (var i = 0; i <= 10; i++) {
  var div = document.getElementById("mydiv");
  div.innerHTML = div.innerHTML + "<br/>" + i;
}
<div id="mydiv"></div>

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You are over-writing or replacing the contents. You need to append, so you can use += operator instead of =.

<div id="mydiv"></div>
<script>
  var i = 0;
  for (i=0; i<=10; i++){
    document.getElementById("mydiv").innerHTML += i + "<br>";
  }
</script>

Upvotes: 0

user2182349
user2182349

Reputation: 9782

Each time your loop ran, it overwrite innerHTML for the div.

This implementation starts with an empty string for html, then uses += to concatenate the counter and <br> on each iteration.

    var i = 0;
    var html = '';
    for (i=0; i<=10; i++){
        html += i + '<br>';
    }
    document.getElementById("mydiv").innerHTML = html;

Upvotes: 2

Related Questions