Skip to main content

Template Element

Web Components: Template Element


What is a built-in HTML template element?

View Answer:
Interview Response: A built-in ‹template› element is used to store HTML markup templates. Although the browser ignores its contents and checks for syntactic validity, we may access and utilize it in JavaScript to build additional components. We could build an invisible element anywhere in HTML to store HTML markup. The ‹template› element's content may be any good HTML, even though it ordinarily requires an enclosing tag. We may also utilize styles and scripts within our templates without influencing the document's load time. The browser considers ‹template› content to be "out of the document": styles are not applied, scripts do not execute, and ‹video autoplay› is not activated. When we enter the content into the document, it becomes live (styles get applied, scripts execute, and so on).

Code Example:

<template>
<tr>
<td>Contents</td>
</tr>
</template>

<template>
<style>
p {
font-weight: bold;
}
</style>
<script>
alert('Hello');
</script>
</template>

What happens when we insert template content into the DOM?

View Answer:
Interview Response: When we insert template content into the DOM, it is available in its content property as a DocumentFragment, a special DOM node. We can treat it as any other DOM node, except for one unique property; its children insert instead when we insert it somewhere in the document. We can also insert the template content into the Shadow DOM in the same fashion.

Code Example:

<template id="tmpl">
<script>
alert('Hello');
</script>
<div class="message">Hello, world!</div>
</template>

<script>
let elem = document.createElement('div');

// Clone the template content to reuse it multiple times
elem.append(tmpl.content.cloneNode(true));

document.body.append(elem);
// Now the script from <template> runs
</script>