5

Not a duplicate of Template tag content is empty - A bug in Angular, while my question is about Vanilla Js.


I am working on a ThingsBoard widget. In the HTML tab, I have this simple template:

<template id="myTemplate">
  <div>Test</div>
</template>

In the JS tab, I am trying to get the contents of this template (to eventually clone it):

const template = document.querySelector("#myTemplate");
console.log(template.content);

However, I am getting an empty DocumentFrgament: Empty document-fragment

This is very strange since when I run it outside of ThingsBoard (for example here on a StackOverflow snippet), I do get the contents of the template:

const template = document.querySelector("#myTemplate");
console.log(template.content);
<template id="myTemplate">
  <div>Test</div>
</template>

Non-empty ducment-fragment

Any ideas?

1 Answer 1

7

If your ThingsBoard example is using React or a similar DOM library, it might be programmatically creating the DOM, which could cause this issue.

When a <template> is constructed programmatically, using appendChild, the content remains empty. For example:

const template = document.createElement('template');
template.appendChild(document.createElement('div'));
console.log(template.content); // #document-fragment (empty)

Instead of template.appendChild, you must use template.content.appendChild for it to work correctly.

I hope this helps in some way!

3
  • Thank you! Could you explain this behavior to me? Why would content remain empty when the template is constructed programmatically? Feb 1, 2022 at 13:24
  • 1
    Apparently, when the HTML parser sees the <template> tag, it transfers all children into the content document fragment. The template's actual children will be empty. Same happens if you set template.innerHTML. But if you append children to the template programmatically, they do not automatically transfer to the content fragment, which is surprising. It seems like this should be fixed, but there might be some valid reason why they don't want to change it. Feb 1, 2022 at 18:36
  • Thanks a lot. This was super helpful in debugging a issue. Sep 12, 2023 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.