简体   繁体   中英

How to create template element dynamically with DOM operations

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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM