I like to create a HTML template element dynamically with JavaScript DOM operations. Something like this:
const template = document.createElement("template")
const div = document.createElement("div")
template.append(div)
However, when using append
the div container won't be available in the templates content
property.
Instead, you have to use innerHTML
like this:
const template = document.createElement("template")
template.innerHTML = "<div></div>"
This does work because innerHTML
has a special behavior implemented for template tags (see https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Operational_details).
However, innerHTML
comes with some downsides and so the question is: How do you use template tag with content created with document.createElement
?
One aspect here is that some JavaScript frameworks (i.e. angular and react) do use document.createElement
internally to create the DOM tree. This makes it nearly impossible to use the template tag with these frameworks.
As an author of a web component that uses the template tag I'd like to support framework users but at the moment I don't see any way of doing so and I'm starting to thinking about removing the template tag altogether. On the other hand I can't imagine that using innerHTML
is the only way here and that the authors of the web component standards haven't thought about this so there must be something I'm overlooking here.
You are doing:
const template = document.createElement("template");
const div = document.createElement("div");
template.appendChild(div);
You should do:
const template = document.createElement("template");
const div = document.createElement("div");
template.content.appendChild(div);
Note You might as well do append here, you are not using the return value.
And append can take TextNodes and multiple parameters:
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append