Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
inserting elements from an array to a div's innerHTML using forEach()

I'm basically trying to first clear the form div by saying form.innerHTML = ''. Then when I try to insert one by one the elements from an array back to the form div using forEach() on the array, It just sets the innerHTML to the last element of an array.

Here's my JavaScript code :

 form.innerHTML = '';
 userCorrectAnswers.forEach(e => {
     let cA = e.innerHTML;
     form.innerHTML = cA;
 });

Need to know how can I add all the elements from that array to the innerHTML of the form.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Since userCorrectAnswers is an Array of Elements — use Element.append()

 form.append(...userCorrectAnswers);

// DOM utility functions:
 
 const EL = (sel, par) => (par||document).querySelector(sel);
 const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
 
 // Task Example:
 
 const form = EL("#form");
 
 const userCorrectAnswers = [
   ELNew("div", {textContent:"Lorem"}),
   ELNew("div", {textContent:"Ipsum"}),
   ELNew("div", {textContent:"Dolor"}),
 ];
 
 form.append(...userCorrectAnswers);
<div id="form"></div>

The above example using .append() used to move newly created or existing elements into another Element. Such will preserve any previously assigned Elements data or Events.

If you don't want to move your elements but clone them instead, use Element.cloneNode(true) like:

form.append(...userCorrectAnswers.map(el => el.cloneNode(true)));

To reduce an Array to String, use Array.prototype.reduce()

 form.innerHTML = userCorrectAnswers.reduce((str, el) => str += el.innerHTML, "");

// DOM utility functions:
 
 const EL = (sel, par) => (par||document).querySelector(sel);
 const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
 
 // Task Example:
 
 const form = EL("#form");
 
 const userCorrectAnswers = [
   ELNew("div", {textContent:"Lorem"}),
   ELNew("div", {textContent:"Ipsum"}),
   ELNew("div", {textContent:"Dolor"}),
 ];

form.innerHTML = userCorrectAnswers.reduce((html, el) => html += el.outerHTML, "");
<div id="form"></div>

The above example is not the best one since it just copies the HTML String, ignoring any previously Elements-assigned Event or data.

It makes use of outerHTML (instead of innerHTML) to include the selected target element tag as well as its contents. Use innerHTML if needed otherwise.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you really want to do this via HTML text, build up all of the text then have the browser parse it all at once:

form.innerHTML = userCorrectAnswers.map(e => e.innerHTML).join("");

Note that that takes the inner HTML of the elements. If you wanted the elements themselves, not just their contents, that would be outerHTML:

form.innerHTML = userCorrectAnswers.map(e => e.outerHTML).join("");
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^

But if that's what you're doing, you might consider copying the elements instead via cloneNode:

form.innerHTML = "";
for (const element of userCorrectAnswers) {
    form.appendChild(element.cloneNode(true));
}

...so there's no need to first create an HTML string from the element, and then parse it again to put it in the form.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda