The <template> element is used for store html that should not render until used. You will run into it while reading other people’s HTML, and it is useful to know what job it does before copying the code.
What does <template> mean?
Store HTML that should not render until used. The tag gives the browser a specific kind of content to work with. It is more helpful to choose a tag for its meaning than because of its default look.
The fragment inside template is inert until a script clones or inserts it.
A working HTML example
Here is a small example you can place in an HTML page and inspect in your browser:
<template id="message-template">
<li class="message">
<strong class="message-title">New message</strong>
</li>
</template>
<ul id="messages"></ul>
<script>
const messageTemplate = document.getElementById("message-template");
document.getElementById("messages").append(messageTemplate.content.cloneNode(true));
</script>
Reading the example
Find the <template> part first. Notice which elements are around it and how its content or attributes are connected to those other elements.
In this example, <template> appears alongside script, custom elements, or shadow DOM. That context is often just as important as the element itself.
The browser builds its document from these relationships. Any CSS changes appearance, while interactive JavaScript behavior must be provided separately when the example includes it.
When should you use it?
Use <template> when you want to store html that should not render until used. A sensible example of this on a real website is the markup shown above; it gives the browser and accessibility tools a clearer job to work with.
Common companions are script, custom elements, or shadow DOM. Check the nesting requirements before moving the element into a different location.
Try it yourself
Clone the template twice and inspect where the cloned nodes appear.
Compatibility note: Customizable select features and component features have specific browser or shadow-DOM requirements. Use a working native fallback and test your target browsers.
Common Beginner Mistakes
- Elements inside template are not visible page content until inserted.
- Picking
<template>only because it looks a certain way instead of checking what it means. - Forgetting to inspect the surrounding markup when an element does not behave as expected.
Key Takeaways
<template>helps store html that should not render until used.- The fragment inside template is inert until a script clones or inserts it.
- Start with meaningful markup, then add styling or scripting only when the page needs it.