HTML - Template Element (Scripted HTML Fragment)

1 - About

The template element is an HTML element that supports templating.

It creates:

A template fragment is not rendered, but stored until it is instantiated via JavaScript
When use in conjunction with a custom element and the shadow dom, the code created is called a web component.

3 - Example

3.1 - Basic

Template without placeholder

  • Template

<template id="template-id">
    p {
      color: white;
      background-color: #666;
      padding: 5px;
  <p>A template that appears only if Javascript add it to the page</p>

  • Javascript will add the template content

let template = document.getElementById('template-id');
let templateContent = template.content;
// the second append has no effect

  • Result:

3.2 - Loop

Example from the specification

  • The template.

<template id="template"><p>Smile!</p></template>

The p element is not a child of the template in the DOM; it is a child of the DocumentFragment returned by the template element's content IDL attribute.
  • The javascript.

let num = 3;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.textContent += fragment.lastChild.textContent;

  • The result:

3.3 - Slot

4 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap