HTML <template> Tag

The HTML <template> tag allows you to declare fragments HTML fragments that can be cloned and inserted into the document by script.

The <template> tag allows you to declare HTML fragments that are not used when the document loads, but can be used later (upon a given user action for example).

The contents of the <template> element are not part of the document until you use it. Therefore, until you use it, none of its contents are downloaded, and you can't reference it via the DOM.

When the contents of the <template> element are used, they are cloned and inserted into the DOM. Therefore, you can use it multiple times, and you can even add to its contents.

Syntax

The <template> tag is written as <template></template> with the template content between the start and end tags.

The global id attribute can be used so that scripts can refer to the element.

Like this:

Example

Basic Usage

Here's an example of the <template> element being used in conjunction with JavaScript. Clicking the button will clone the contents of the <template> element and insert it into the DOM.

Add Table Rows

Here's an example of adding rows to an editable table using the <template> tag.

Attributes

Attributes can be added to an HTML element to provide more information about how the element should appear or behave.

The <template> element accepts the following attributes.

AttributeDescription
None 

Global Attributes

The following attributes are standard across all HTML elements. Therefore, you can use these attributes with the <template> tag , as well as with all other HTML tags.

For a full explanation of these attributes, see HTML 5 global attributes.

Event Handlers

Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain "event" occurs. Each event handler content attribute deals with a different event.

Most event handler content attributes can be used on all HTML elements, but some event handlers have specific rules around when they can be used and which elements they are applicable to.

For more detail, see HTML event handler content attributes.