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

263
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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