Home > OS >  inserting elements from an array to a div's innerHTML using forEach()
inserting elements from an array to a div's innerHTML using forEach()

Time:03-06

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.

CodePudding user response:

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.

CodePudding user response:

Since userCorrectAnswers is an array of Elements you could just 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>

Otherwise, if you want to reduce an Array to String, use Array.prototype.reduce()

 form.innerHTML = userCorrectAnswers.reduce((html, el) => html  = 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.innerHTML, "");
<div id="form"></div>

See the above's "Show code examples" to explore the slight differences between the two approaches.

  • Related