jQuery: Simple template solution without plugins

Published by Profile Image LGK on 14 June, 2016
This is a great and simple solution to use HTML templates in your jQuery code.

First create a template area in your HTML document:
<section class="tpl-area">

To make sure that the template area is not visible add this CSS:
.tpl-area * {
display: none !important;

Make a template:
<section class="tpl-area">
<article id="tpl-hello">
<h1>Hello, <span class="hello-text"></span>!</h1>

Place a container where the output should appear. Of course outside of .tpl-area:
<div id="output"></div>

Use the template in your code:
var names = ["Luna", "Dean", "Dobby"];

// Make sure the output container is empty

for (var i = 0; i < names.length; i++) {
// Clone the template
var element = $("#tpl-hello").clone();

// And fill it

// Place this copy

You can find a live demo here: