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

2 Answers 2

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];
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

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.