LessonLesson 30 of 34

Templates, data attributes, and reusable components

Clone inert templates safely, keep identifiers unique, and understand where web components add value and complexity.

Advanced4 min readLearn · Practice · Review

Published by HTML Code Runner · AI-assisted material · Independent editorial review pending · Editorial policy

On this page

Learning objectives

Clone template content; populate text without parsing untrusted HTML; explain the roles of custom elements, shadow DOM, and slots.

Prerequisites

Understand DOM selection, JavaScript objects, classes and IDs, and accessible naming.

A template is a reusable fragment, not a visible card

The template element holds markup that is not rendered as ordinary document content. Its content property exposes a document fragment that a script can clone and insert. This lets you keep repeated structure in HTML rather than constructing long strings of tags in JavaScript.

Cloning copies the structure, not your application’s data model. After making a clone, populate its fields and append it to the intended container. Be careful with IDs inside repeated templates: cloning the same ID into several cards creates duplicate identities and breaks label or ARIA relationships. Prefer local class selectors for repeated fields, then generate unique IDs only where a relationship needs one.

Separate data from executable markup

Use textContent when inserting a title, name, or description as plain text. Assigning arbitrary data to innerHTML makes the browser parse it as markup, which can create an injection risk. Safe output handling depends on the destination context; a text field and a URL attribute require different validation and escaping decisions.

Data attributes provide custom string metadata on elements. A data-topic value can help a filtering script or identify a component state. The dataset interface exposes these values to JavaScript, with hyphenated attribute names mapped to property names. Data attributes are public page data, not hidden credentials or a substitute for application authorization.

Keep the HTML meaningful before enhancement where possible. If important content exists only in a template and scripts never run, the user may see an empty page. For essential article content, server-rendered HTML is often a stronger baseline; templates can enhance repeated interactive pieces.

Know what web components do and do not provide

Custom elements define reusable element behavior. Their names use a hyphen, helping distinguish them from built-in HTML elements. Shadow DOM can encapsulate a component’s internal tree and styling, while slots provide insertion points for light-DOM content. These mechanisms can improve reuse but do not automatically supply accessible semantics or a good public API.

Encapsulation is not a security boundary for secrets. Components still need keyboard behavior, naming, focus management, and appropriate native elements inside their implementation. Cross-boundary labeling and form participation require deliberate design. Choose a web component when reuse and encapsulation justify it, not merely to replace a straightforward article or button with more code.

Working example

<template id="book-template">
  <article class="book-card"><h2 class="book-title"></h2><p class="book-note"></p></article>
</template>
<div id="book-list"></div>

Another example

<article class="lesson-card" data-topic="forms" data-level="intermediate">
<h2>Form validation</h2>
<p>Understand constraints and useful error messages.</p>
</article>

Expected output

The live script clones the template twice, inserts plain-text titles and notes, and appends two cards. The template itself remains invisible. The data-attribute example displays ordinary content while exposing extra filter metadata to scripts.

Common mistakes

Do not append template.content directly if you need to reuse it without consuming its nodes. Do not clone duplicate IDs into every card. Do not assume shadow DOM sanitizes untrusted strings or that a custom tag inherits button keyboard behavior.

Accessibility and browser notes

Keep native headings and controls inside components. Test the final accessibility tree, not just the template source. Repeated controls need distinct names when their actions apply to different items, such as Remove Canal walk rather than several identical Remove buttons.

Practice

Clone a template and insert a user-provided title as text rather than HTML.

Review the solution and reasoning
const fragment = document.querySelector("#book-template").content.cloneNode(true);
fragment.querySelector(".book-title").textContent = userProvidedTitle;
document.querySelector("#book-list").append(fragment);

CloneNode(true) copies the fragment’s descendants. TextContent treats the supplied title as text, so a string containing angle brackets does not become new page markup. Other fields still need their own context-appropriate validation.

Related lessons

Specifications and further reading

One more skill in your toolkit.

Finished the explanation and exercise? Save your progress.