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

151
Views
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 answers
Answer question

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 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!