pjk_ok
pjk_ok

Reputation: 947

Print All For Loop Array Values to Inner HTML

I would like to print some array values to the screen inside a container div. The loop below is only printing the final array value "dog" to the screen.

I can't seem to work out the problem here?

JS

var arr = ["mouse", "cat", "dog"];
var holder = document.getElementById("holder");

for ( var i=0; i < arr.length; i+=1 ) {

holder.innerHTML = "<p>" + arr[i] + "</p><br/>" ;

}

HTML

<div id="holder"></div>

Upvotes: 0

Views: 8716

Answers (1)

BuzzRage
BuzzRage

Reputation: 184

Try with += in holder.innerHTML = "<p>" + arr[i] + "</p><br/>" ;, otherwise it will overwrite the line for each iteration.

var arr = ["mouse","cat","dog"];
var holder = document.getElementById("holder");
for(var i=0; i < arr.length; i++)
  holder.innerHTML += "<p>"+arr[i]+"</p><br>";
<div id="holder"></div>

Upvotes: 4

Related Questions