This is the proper way to have HTML templates and clone them in Javascript.
First add the template to your HTML:
<template id="example-template">
<div class="example">
<p>Hello</p>
<p>World</p>
</div>
</template>
Then get a reference to the template element during JS startup:
const template = document.getElementById("example-template").content.querySelector(".example");
Notice that <template>
is just used as way to properly hide the element used as the actual template. It has no other real need to be here. You could even get rid of <template>
altogether and add a hidden
CSS class to example
, but then you'd have to remember to remove that class from the resulting element after it is cloned (I prefer the <template>
solution).
Once the template is ready, you can then clone as much as you like:
const element = template.cloneNode(true);
element.setAttribute("id", "my-newly-created-element");
document.body.appendChild(element);