0

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>
1
  • Append to innerHTML (+= not =) at the moment your overwriting it. Commented Jan 18, 2018 at 16:46

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.