The reason is because tmpl.content
is an element, and you can’t append an element to another source when it is already appended to something. Try doing this instead:
let elem = document.createElement("div");
elem.append(tmpl.content);
document.body.append(elem);
let elem2 = document.createElement("div");
elem2.append(tmpl.content);
document.body.append(elem2);
It won’t work, because tmpl.content
has already been appended to something else.
This is an example of using <template>
element.
In the below code, I just wrote a div
element inside a template
element
<template id="tmpl">
<div class="message">Hello, world!</div>
</template>
And then I just used that template
in the script below, a normal use case of template
<script>
let elem = document.createElement('div');
elem.append(tmpl.content.cloneNode(true));
document.body.append(elem);
</script>
We can see that template.content
(basically a document fragment) was cloned before using it.
And explanation on javascript.info says that:
Template content was cloned to reuse it multiple times
My question is why we can’t reuse it without cloning?. Can you give a deep insight into this?