michal.b
michal.b

Reputation: 31

Why does the "innerHTML" property with <br> doesn't create new lines?

I'm trying to build a pyramid of "*", and I can see only the last line of it, while with the alert I can see every line. anybody know what is wrong with my code?

function build(){
        var x = document.hi.floor.value;
        //alert(x);
        var i;
        var bil= "";
        for(i=0; i<x; i+=1){
            bil = bil + "*";
            //alert(bil);   
            document.querySelector(".py").innerHTML= bil +"<br/>";  
        }           
    }

Here is a fiddle.

Upvotes: 1

Views: 132

Answers (1)

trincot
trincot

Reputation: 350034

You should concatenate your results in the loop, and then output the result afterwards, like this:

function build(){
    var x = document.hi.floor.value;
    //alert(x);
    var i;
    var bil= "";
    var html = "";
    for(i=0; i<x; i+=1){
        bil = bil + "*";
        //alert(bil);   
        html += bil +"<br/>";  
    }
    document.querySelector(".py").innerHTML= html;
}

You were just overwriting each previous value of innerHTML with the latest value of bil. So in the end you only had ***<br/> (for x = 3), and the line-break didn't really show as there was nothing following it.

Here is a fiddle.

Upvotes: 1

Related Questions