Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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]);
  }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can't reuse a single element, instead you have to create a new one for each step inside the loop. And a <div> needs either some size or some content to actually appear.
So the minimal changes could be the 3 lines with comments:

function myFunc()
{
  var container = document.getElementById("container");
  //var newDiv = document.createElement("div"); // <-- you can't reuse

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

  for (var i = 0; i < 3; i++)
  {
      var newDiv = document.createElement("div"); // <-- have to create a new one
      newDiv.innerHTML="&nbsp;"; // <-- a completely empty, dimensionless div won't appear
      divArray.push(newDiv);
      var temp = divArray[i];
      temp.setAttribute("style", "background-color: "+ colorArray[i]);
      container.appendChild(divArray[i]);
  }
}
<section id="container"></section>
<button onclick="myFunc()">BUTTON 1</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

I have updated your snippet with syntax correction. Since you are adding new elements to be appended, it's better to create the div element within 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.textContent = i;
    divArray.push(newDiv);

    newDiv.setAttribute("style", "background-color: " + colorArray[i]);

    container.append(newDiv);
  }
}
<section id="container"></section>
<button onclick="myFunc()">BUTTON 1</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda