1

Here's my code:

var never = [1,2,3,4,7];

function please () {
  for (var i = 0; i < never.length; i++) {
    document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
  }
}

I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.

1
  • 2
    You are resetting the innerHTML after each iteration. You need to add + like this document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>"; Commented Feb 25, 2018 at 20:02

2 Answers 2

4

The best way is to append created buttons in container.Each by each

var never = [1,2,3,4,7];

function please () {
  var more=document.getElementById("more");
  for (var i = 0; i < never.length; i++) {
    var butt=document.createElement("button");
    butt.innerHTML=never[i];
    more.appendChild(butt);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the most reasonable answer, the other ones are just waste of time.
Add a little more of info, please. Doc for example.
3

By appending to innerHTML instead of assigning, like

var never = [1,2,3,4,7];

function please () {
  for (var i = 0; i < never.length; i++) {
    document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
  }
}

please();
<div id="more">
</div>

1 Comment

Typo answer, lovely!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.