How to use the HTML5 template tag
The HTML5 <template> tag stores inert, reusable HTML content that can be cloned with JavaScript; it remains unrendered until programmatically inserted, making it ideal for dynamically generating elements like product cards without reloading or hardcoding, and it supports advanced features like data attributes and slots for flexible, organized, and performant DOM manipulation.
The HTML5 <template></template>
tag is a handy way to store HTML content that you don’t want to render immediately when the page loads. Instead, you can clone and insert this content later using JavaScript. It's perfect for dynamically adding elements like cards, forms, or list items without hardcoding them repeatedly or fetching HTML from external sources.
Here’s how to use it effectively.
What the template tag does
The <template></template>
element holds content that is:
- Not rendered on the page when the document loads.
- Parsed but inert — scripts inside don’t run, images don’t load, custom elements aren’t upgraded.
- Available for cloning via JavaScript when needed.
This makes it ideal for reusable UI components created on the fly.
Basic usage example
Let’s say you want to dynamically add product cards to a page.
<template id="product-card-template"> <div class="product-card"> <h3 class="product-title"></h3> <p class="product-price"></p> <button>Buy Now</button> </div> </template> <div id="product-container"></div>
Now use JavaScript to clone the template and populate it:
// Get the template and container const template = document.getElementById('product-card-template'); const container = document.getElementById('product-container'); // Function to add a new product function addProduct(title, price) { // Clone the template content const clone = document.importNode(template.content, true); // Update the cloned elements clone.querySelector('.product-title').textContent = title; clone.querySelector('.product-price').textContent = `$${price}`; // Append to the container container.appendChild(clone); } // Add some products addProduct('Laptop', 999); addProduct('Mouse', 25);
Now two product cards appear — created from the template.
Key points when working with templates
Use
document.importNode()
ortemplate.content.cloneNode()
Always clone the.content
of the template (which is aDocumentFragment
). This avoids modifying the original template.Deep clone with
true
Passtrue
as the second argument toimportNode()
orcloneNode()
to ensure all child nodes are copied.Templates are not limited to one use
You can use the same template to create multiple instances across your app.Works well with shadow DOM and web components
Templates are often used inside custom elements to define internal structure.No need to hide templates with CSS
The content inside<template>
is automatically not displayed — nodisplay: none
required.
Advanced: Pre-fill template with data attributes or slots
You can design more flexible templates using data-*
attributes or the <slot>
element (especially useful with web components).
<template id="user-card"> <div class="user-card"> <img src="" alt="" class="avatar"> <h2 class="name"></h2> <span class="role" data-role></span> </div> </template>
Then fill in values including src
, alt
, and data attributes as needed in JavaScript.
Basically, the <template></template>
tag gives you a clean, performant way to manage reusable HTML. It’s not flashy, but it keeps your DOM clean and your dynamic content organized.
The above is the detailed content of How to use the HTML5 template tag. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Catalog ForestProtocol's birth background The innovative technology architecture of interactive tokens (Playable Tokens) CampaignOS: Turn tokens into "playable products" Launchpad and AMM: No curves, no migration, flywheels and fees: Convert usage and revenue into repurchase and destroy CampaignOS's role and value Launchpad and AMM mechanism $FOREST's token economic model Where the value of $FOREST comes from the latest price and market outlook roadmap: From template

Theplaceholderattributeprovidesashorthintininputfieldsthatdisappearswhentypingbegins;1.Itisusedinandelementstoshowexampletextlike"Enteryouremail";2.Thehintisdisplayedonlywhenthefieldisemptyandstyledfaintlybybrowsers;3.Itdoesnotreplacetheele

TheHTML5tagstoresinert,reusableHTMLcontentthatcanbeclonedwithJavaScript;itremainsunrendereduntilprogrammaticallyinserted,makingitidealfordynamicallygeneratingelementslikeproductcardswithoutreloadingorhardcoding,anditsupportsadvancedfeatureslikedataat

CSPenhancesHTML5securitybydefiningtrustedcontentsourcestopreventXSS,clickjacking,andcodeinjection.1.Itrestrictsinlinescriptsandstylesbyblockingthemunless'unsafe-inline',nonces,orhashesareused.2.Itcontrolsexternalresourcesviadirectiveslikescript-src,i

ThetimeelementinHTML5representsdatesandtimesinamachine-readableformat,enhancingaccessibilityandSEO;usethedatetimeattributewithISO-formattedvaluestoprovidesemanticmeaning,especiallyforhuman-friendlytextordurations,ensuringconsistentinterpretationbymac

To implement HTML5 drag and drop, you must first set the draggable="true" of the element, then use e.dataTransfer.setData() to define the drag data through the dragstart event, and listen to the dragover and drop events on the drop target. The dragover must call e.preventDefault() to allow placement. Finally, the data is obtained and operations are performed through getData() in the drop event. The entire process needs to correctly handle data delivery and default behavior, and fully implement the drag and drop function of element.

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

To create a full-screen video background, you need to use HTML5 tags and combine CSS to achieve responsive coverage. First, add elements with autoplay, muted, and loop attributes to HTML to ensure automatic loop playback and compatibility. Then, set position:fixed, width and height to 100%, object-fit:cover to fill the viewport and crop it to avoid deformation. At the same time, set z-index:-1 to place the video at the bottom of the content. In order to improve performance and compatibility, static images should be provided as a downgrade fallback, optimize the video format H.264 encoded MP4 and control the file size. For mobile devices, you can use media
