3

I am trying to dynamically add 4 buttons with different text on each of them using JavaScript. Basically when the person clicks on the initial button, another 4 buttons would pop up.

The text that shows up in each button is coming from an array, the problem is that when I click the button only one button is created with the text from the final string in the array.

What am I doing wrong?

Here's the code I am using:

var btn = document.getElementById("btn");
var option = document.createElement("button");
var optionText = ["Button 1", "Button 2", "Button 3", "Button 4"];

btn.addEventListener("click", function(){
  buttonSelect();
})

function buttonSelect() {
  for(var i = 0; i < optionText.length; i++){
    document.body.appendChild(option);
    option.innerHTML = optionText[i];
  }
}
Christian Lopez
  • 218
  • 3
  • 13

2 Answers2

4

You are only creating one button and then appending it over and over. appendChild doesn't copy the button you created, it takes it from wherever it was and re-attaches it where you specify. So when you use document.body.appendChild(option), it will remove the button from the DOM and re-insert it at the end of the body.

Try this instead:

function buttonSelect() {
  for(var i = 0; i < optionText.length; i++){
    var option = document.createElement("button");
    document.body.appendChild(option);
    option.innerHTML = optionText[i];
  }
}
chowey
  • 9,138
  • 6
  • 54
  • 84
1

You are only creating 1 new element. Try this.

var btn = document.getElementById("btn");
var optionText = ["Button 1", "Button 2", "Button 3", "Button 4"];

btn.addEventListener("click", function(){
  buttonSelect();
})

function buttonSelect() {
  for(var i = 0; i < optionText.length; i++){
    var option = document.createElement("button");
    option.innerHTML = optionText[i];
    document.body.appendChild(option);
  }
}

Basically moving the document.createElement("button") within your for loop will create a new element for each item in your array.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179