Search code examples
javascripthtmlloopsappendchild

JavaScript - How .appendChild() while looping?


When I click on the button, I only get one "div" in the color green. But I would like to have 3 "divs" in red, orange and green with only one click. How can I do this? See my code below:

<!-- HTML CODE -->
<section id="container"></section>
<button onclick="myFunc()">BUTTON 1</button>


// JavaScript Code
function myFunc()
{
  var container = document.getElementById("container");
  var newDiv = document.createElement("div");

  const colorArray = ["red", "orange", "green"];
  var divArray = [];

  for (var i = 0; i < 3; i++)
  {
      divArray.push(newDiv);
      var temp = divArray[i];
      temp.setAttribute("style", "background-color: "+ colorArray[i]);
      container.appendChild(divArray[i]);
  }
}

Solution

  • Do document.createElement inside the loop:

    function myFunc() {
      var container = document.getElementById("container");
      const colorArray = ["red", "orange", "green"];
      var divArray = [];
    
      for (var i = 0; i < 3; i++) {
        var newDiv = document.createElement("div");
        newDiv.classList.add("new-div")
        divArray.push(newDiv);
        var temp = divArray[i];
        temp.setAttribute("style", "background-color: " + colorArray[i]);
        container.appendChild(divArray[i]);
      }
    }
    .new-div {
      outline: 1px solid salmon;
      height: 50px;
      width: 50px;
    }
    <section id="container"></section>
    <button onclick="myFunc()">BUTTON 1</button>