Ericson Willians
Ericson Willians

Reputation: 7845

Can't "print" with .innerHTML using a for loop

I'm just beginning with Javascript and, well, this code is quite obvious and it just don't work and I don't know why, because everything looks fine:

<html>
<head>
</head>
<body>
<h1>This is my first Javascript test.</h1>
<p id = "y">123</p>
<button type = "button" onclick = "do()">Do it!</button>
<script>
var x = ["First Element", "Second Element", "Third Element", "Fourth Element"];
function do() {
    for (var i = 0; i < x.length; i++) {
        document.getElementById("y").innerHTML = x[i] + "<br>";
    }
}
</script>
</body>
</html>

When I click the bloody button, it just don't work. It does not give me the contents of the array on the < p > tag there.

I thank you very much!

Upvotes: 0

Views: 960

Answers (1)

mohkhan
mohkhan

Reputation: 12305

I think what you are trying to achieve can be done by this small change...

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

Also it would be wiser to have "y" stored in a local variable rather than getting it every time.

<script>
var y = document.getElementById("y");
var x = ["First Element", "Second Element", "Third Element", "Fourth Element"];
function do() {
    y.innerHTML = "";
    for (var i = 0; i < x.length; i++) {
        y.innerHTML += x[i] + "<br>";
    }
}
</script>

Upvotes: 3

Related Questions