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

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.

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

Could anyone suggest me a better way of doing this?

Thanks for any responds!

>Solution :

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);
  }
}
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