Home > other >  How to insert result of forEach into html?
How to insert result of forEach into html?

Time:10-20

I have an array that I am iterating over with forEach and I need to add what is output to the console in html using template strings. How can i do this?

const postCategories = arr[index].category;
const postCategory = postCategories.forEach(category => {
  console.log(category.name);
});

const article = `<article >
<div >
      <span>//Here I need to enter the name of the category</span>
</div>
</article>`;

CodePudding user response:

.forEach returns undefined, .map will return to you a result you're after.

I'm going to assume that each category contains at least a name key... Additionally, I'm assuming you want to insert the result of that at the end of all the iterations

const postCategories = arr[index].category;
const postCategory = postCategories.map(category => {
  return `<div>${category.name}</div>`;
});

const article = `
  <article >
    <div >
        ${postCategory}
    </div>
  </article>
`;

Note: This is my preferred format for multiline strings using "` `.

The output would be something like this:

<article >
  <div >
      <div>Category 1</div>
      <div>Second Category</div>
      <div>Category 3</div>
  </div>
</article>

CodePudding user response:

You just need to inject in the body with insertAdjacentHTML.

beforeend means just before the body end tag.

const postCategories = ['one', 'two', 'three']
const postCategory = postCategories.forEach(category => {
  const template = `<article >
    <div >
      <span>${category}</span>
    </div>
  </article>`
  document.body.insertAdjacentHTML('beforeend', template)
});

CodePudding user response:

One possibility: map the array using a function to fill in a string. Something like:

const article = txt => `<article >
  <div ><span>${txt}</div>
</article>`;
// map to new array
const texts = [`hello`, `world`].map(t => article(t));

document.body.insertAdjacentHTML(`beforeend`, texts.join(``));

// use forEach
[`goodbye`, `world`].forEach(t => 
  document.body.insertAdjacentHTML(`beforeend`, article(t)) );

  • Related