Templates and Web Components
What Is It?
A template stores HTML without displaying it. JavaScript copies it when you need it. Web Components let you create reusable custom elements.
What the Tags Mean
template: hidden reusable markup.cloneNode(true): copies the template content.slot: a place for supplied content in a Web Component.- Custom element names include a hyphen, such as hello-note.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Templates and Web Components</title>
</head>
<body>
<template id="card">
<p>Welcome to the club!</p>
</template>
<div id="cards"></div>
<script>
const copy = document.getElementById("card").content.cloneNode(true);
document.getElementById("cards").append(copy);
</script>
</body>
</html>Browser preview
What you see: The script copies the paragraph and adds it to the page. The template alone would show nothing.
Example 2: Another Use
A custom element can provide the same behavior wherever you use its tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Templates and Web Components</title>
</head>
<body>
<hello-note></hello-note>
<script>
class HelloNote extends HTMLElement {
connectedCallback() { this.textContent = "Hello from a custom element!"; }
}
customElements.define("hello-note", HelloNote);
</script>
</body>
</html>Browser preview
Simple Tip
This is an advanced topic. Learn basic tags and JavaScript first. You can return to templates later.
Try It Yourself
Change the paragraph inside the template.