Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
JavaScript - ¿Cómo .appendChild() mientras se repite?

Cuando hago clic en el botón, solo obtengo un "div" en color verde. Pero me gustaría tener 3 "divs" en rojo, naranja y verde con un solo clic. ¿Cómo puedo hacer esto? Ver mi código a continuación:

 <!-- 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 answers
Answer question

0

Haz document.createElement dentro del ciclo:

 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 Report

0

No puede reutilizar un solo elemento, sino que debe crear uno nuevo para cada paso dentro del bucle. Y un <div> necesita algo de tamaño o algo de contenido para aparecer.
Entonces, los cambios mínimos podrían ser las 3 líneas con comentarios:

 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 Report

0

He actualizado su fragmento con corrección de sintaxis. Dado que está agregando nuevos elementos para agregar, es mejor crear el elemento div dentro del bucle.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!