Christian Lopez
Christian Lopez

Reputation: 218

How to add multiple buttons with a for loop/click event in JavaScript?

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];
  }
}

Upvotes: 3

Views: 5636

Answers (2)

Charlie Fish
Charlie Fish

Reputation: 20496

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.

Upvotes: 1

chowey
chowey

Reputation: 9836

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];
  }
}

Upvotes: 4

Related Questions