Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I render html with insertAdjacentHTML

How can I render components with pure javascript? I used insertAdjacentHTML and forEach to render a list with objects but the objects appeared undefined.

object list

const liRender = document.getElementById('ul-component')

function render() {

itens.forEach(() => {
    liRender.insertAdjacentHTML("afterbegin",
 ` <li class="products-list__item">
    <div class="products-list__item-thumbnail">
      <img
        class="product__thumbnail"
        src=${itens.img}>
        <div class="products-list__item-main-content">
        <h4 class="product__name">
          ${itens.modelo}
        </h4>
        <p class="product__description">
          ${itens.description}
        </p>
        <div class="products-list__item-action-buttons">
        <button class="button" data-open-modal="1">Detalhes</button>
        </div>
    </div>
  </li>
`

    )
})
}

export function Component() {
render()
}

result list return undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your forEach needs iten passed within it. Like the following,

itens.forEach((iten) => {

Then you refer to each property like so,


<p class="product__description">
  ${iten.description}
</p>
const liRender = document.getElementById('ul-component')
const itens = [{
    modelo: 'test',
  description: 'description',
  img: 'image'
},
{
    modelo: 'test 2',
  description: 'description 2',
  img: 'image'
},
{
    modelo: 'test 3',
  description: 'description 3',
  img: 'image'
}];

function render() {

  itens.forEach((iten) => {
    liRender.insertAdjacentHTML("afterbegin",
      ` <li class="products-list__item">
    <div class="products-list__item-thumbnail">
      <img
        class="product__thumbnail"
        src=${iten.img}>
        <div class="products-list__item-main-content">
        <h4 class="product__name">
          ${iten.modelo}
        </h4>
        <p class="product__description">
          ${iten.description}
        </p>
        <div class="products-list__item-action-buttons">
        <button class="button" data-open-modal="1">Detalhes</button>
        </div>
    </div>
  </li>
`

    )
  })
}


render();
<ul id='ul-component'>

</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading