views:

123

answers:

2

Hi, the following is code to create a sequential list of numbers from 1 to 10. I'd like to take this list and output in the div "pagination" using innerHTML. However, when I execute the script, the only thing that is outputted is the number 10. When I overwrite the page using document.write instead, it outputs the whole list. Can someone tell me what I'm doing wrong? Thanks.

function generateNumbers() {
    var numbers = new Array();

    // start generating numbers
    for(var i = 1; i <= 10; i+= 1) {
        numbers.push( i );
    }

    // print numbers out.
    for(var i = 0; i < numbers.length; i++) {
        document.getElementById("pagination").innerHTML = numbers[i] + "<br>";
    }
}

and in the HTML:

<div id="pagination"></div>
+5  A: 

Well, you override innerHTML in every step.
Try:

document.getElementById("pagination").innerHTML += numbers[i] + "<br>";

Or better:

// no for loop
document.getElementById("pagination").innerHTML = numbers.join("<br>");
Kobi
ah, stupid me. thanks a lot!
George
A: 
for(var i = 0; i < numbers.length; i++) {
    document.getElementById("pagination").innerHTML = numbers[i] + "<br>";
}

This replaces the innerHTML every single time through the loop, so you only see the last iteration.

Try making that = a +=.

Or even better, build it up in a string and set the innerHTML just once with that final string. This will be faster since it only has to parse the string as HTML once instead of 100 times.

Squeegy
how would you build it up in a string and then set innerHTML to that? Would it just be setting numbers[i] + "<br>" as a variable?
George
like: `var html = '';` then in the loop: `html += numbers[i] + '<br>';`. Although the `join` method above is cleaner all around.
Squeegy
ah, I see. Thank you very much.
George