Home > Enterprise >  How can I render html with insertAdjacentHTML
How can I render html with insertAdjacentHTML

Time:07-29

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 >
    <div >
      <img
        
        src=${itens.img}>
        <div >
        <h4 >
          ${itens.modelo}
        </h4>
        <p >
          ${itens.description}
        </p>
        <div >
        <button  data-open-modal="1">Detalhes</button>
        </div>
    </div>
  </li>
`

    )
})
}

export function Component() {
render()
}

result list return undefined

CodePudding user response:

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

itens.forEach((iten) => {

Then you refer to each property like so,


<p >
  ${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 >
    <div >
      <img
        
        src=${iten.img}>
        <div >
        <h4 >
          ${iten.modelo}
        </h4>
        <p >
          ${iten.description}
        </p>
        <div >
        <button  data-open-modal="1">Detalhes</button>
        </div>
    </div>
  </li>
`

    )
  })
}


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

</ul>

  • Related