Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
What is the easiest to create a module (which contain lots of html elements) instead of using appendChild?

I am trying to create a module that contains a huge group of html elements in Javascript and use for loop to create many of the module. The below is an example (I have more of html elements in the module, but in order to a create a minimal example, I reduce most of them.

function create() {
  for (let i = 0; i < 20; i++) {
    let img = document.createElement('img')
    //img.src = source[i].url
    let pho = document.createElement('div')
    pho.className = 'pho'
    let button = document.createElement('button')
    button.textContent = "♡"
    let border = document.createElement('div')
    let hr = document.createElement('hr')
    pho.appendChild(button)
    pho.appendChild(img)
    border.appendChild(hr)
    border.appendChild(pho)
    document.body.appendChild(border)
  }
}
create()

In the above example, I am trying to use appendChild to create a parent element (border) that contain several children elements.

It works find, but the code looks too massy and hard to deal if I have more of them.

Could anyone suggest me a better way of doing this?

Thanks for any responds!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Use an HTML string instead?

const createBorder = (url) => {
  const div = document.body.appendChild(createElement('div'));
  div.innerHTML = `
    <hr>
    <div class="pho">
      <button>♡</button>
      <img>
    </div>
  `;
  // avoid XSS vulnurabilities by not interpolating the dynamic value
  // directly into the HTML string
  div.querySelector('img').src = url;
};
function create() {
  for (let i = 0; i < 20; i++) {
    createBorder(source[i].url);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda