Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
¿Cuál es la forma más fácil de crear un módulo (que contiene muchos elementos html) en lugar de usar appendChild?

Estoy tratando de crear un módulo que contenga un gran grupo de elementos html en Javascript y uso for loop para crear muchos de los módulos. El siguiente es un ejemplo (tengo más elementos html en el módulo, pero para crear un ejemplo mínimo, reduzco la mayoría de ellos.

 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()

En el ejemplo anterior, intento usar appendChild para crear un elemento principal ( border ) que contiene varios elementos secundarios.

Funciona encontrar, pero el código parece demasiado masivo y difícil de manejar si tengo más de ellos.

¿Alguien podría sugerirme una mejor manera de hacer esto?

¡Gracias por cualquier respuesta!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¿Usar una cadena HTML en su lugar?

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!