Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

HTML <template> class Attribute

The class attribute assigns one or more classnames to the <template> tag.

Classes on templates are generally only used by JavaScript to locate the proper template.

Example

#

A class attribute identifying a <template> element.

<style>
 .status-template{background:aliceblue;}
</style>

<template class="status-template">
 <select>
  <option value="pending">Pending</option>
  <option value="approved">Approved</option>
  <option value="rejected">Rejected</option>
 </select>
</template>

Using class

Multiple classnames are separated by a space.

JavaScript uses classes to access elements by classname.

Tip:  class is a global attribute that can be applied to any HTML element.


Syntax

<template class="classnames">

Values

#

Value Description
classnames One or more space-separated class names.

More Examples

A class attribute identifying a <template> element.
Clicking the button locates the template (by classname) and adds it to the list.


  • Item 1
<button onclick="addItem()">Add List Item</button>
<br />

<ul id="list">
  <li>Item 1</li>
</ul>
  
<template class="item-template">
  <li></li>
</template>

<script>
  var itemCount = 1;

  let addItem = () => {
     itemCount++;
  
     let template = document.getElementsByClassName("item-template")[0];  
     let content = template.content;
     content.querySelector('li').textContent = "Item " + itemCount;
  
     let newRow = template.content.cloneNode(true);

     document.getElementById("list").appendChild(newRow);
  }
</script>

Code explanation

The class attribute assigns the class item-template to the <template>.

Repeatedly clicking the button locates the <template> using the class.

It displays the <template> content inside the <ul>.


Browser support

Here is when class support started for each browser:

Chrome
26.0 Mar 2013
Firefox
22.0 Jun 2013
IE/Edge
13.0 Nov 2015
Opera
15.0 Jul 2015
Safari
9.0 Sep 2015

You may also like

 Back to <template>
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

Guides