HTMLTemplateElement: content property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2015.
Thecontent property of theHTMLTemplateElement interface returns the<template> element's template contents as aDocumentFragment. This content'sownerDocument is a separateDocument from the one that contains the<template> element itself — unless the containing document is itself constructed for the purpose of holding template content.
TheNode.cloneNode() andDocument.importNode() methods both create a copy of a node. The difference is thatimportNode() clones the node in the context of the calling document, whereascloneNode() uses the document of the node being cloned. The document context determines theCustomElementRegistry for constructing any custom elements. For this reason, usedocument.importNode() to clone thecontent fragment so that custom element descendants are constructed using the definitions in the current document, rather than the separate document that owns the template content. See theNode.cloneNode() page's examples for more details.
In this article
Value
Examples
>Using importNode() with template content
const templateElement = document.querySelector("#foo");const documentFragment = document.importNode(templateElement.content, true);// Now you can insert the documentFragment into the DOMThe ownerDocument of template content
For<template> elements created in the context of a normal HTML document, theownerDocument of thecontent is a separate, freshly created document:
const template = document.createElement("template");console.log(template.content.ownerDocument === document); // falseconsole.log(template.content.ownerDocument.URL); // "about:blank"If the<template> element is created in the context of a document that itself was created for the purpose of holding template content, then theownerDocument of thecontent is the same as that of the containing document:
const template1 = document.createElement("template");const docForTemplate = template1.content.ownerDocument;const template2 = docForTemplate.createElement("template");console.log(template2.content.ownerDocument === docForTemplate); // trueSpecifications
| Specification |
|---|
| HTML> # dom-template-content-dev> |