Skip to main content

HTML Templates in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use HTML templates in JavaScript DOM to create reusable structures, improving the maintainability and readability of your web applications.

What are HTML Templates?

HTML templates are a way to define reusable HTML structures with the <template> tag. They are not rendered on the page by default, but can be cloned and added to the DOM using JavaScript.

Example: Creating an HTML Template

Consider the following HTML template:

<template id="user-card-template">
<div class="user-card">
<h2 class="user-name"></h2>
<p class="user-email"></p>
</div>
</template>

This template defines a reusable structure for a user card, including a name and an email address.

Using the HTML Template

To use the HTML template, we will create a function that clones the template and populates it with data:

function createUserCard(name, email) {
const template = document.getElementById('user-card-template');
const userCard = template.content.cloneNode(true);

userCard.querySelector('.user-name').textContent = name;
userCard.querySelector('.user-email').textContent = email;

return userCard;
}

The createUserCard function accepts name and email arguments and performs the following steps:

  1. Get the template element using getElementById.
  2. Clone the template content using cloneNode(true).
  3. Populate the cloned template with data using querySelector and textContent.
  4. Return the populated template.

Example: Adding User Cards to the Page

Now that we have our createUserCard function, we can use it to add user cards to the page:

HTML
<div id="user-container"></div>
JavaScript
const userContainer = document.getElementById('user-container');

const user1 = createUserCard('John Doe', 'john.doe@example.com');
const user2 = createUserCard('Jane Doe', 'jane.doe@example.com');

userContainer.appendChild(user1);
userContainer.appendChild(user2);

After executing this code, the updated HTML structure will be:

<div id="user-container">
<div class="user-card">
<h2 class="user-name">John Doe</h2>
<p class="user-email">john.doe@example.com</p>
</div>
<div class="user-card">
<h2 class="user-name">Jane Doe</h2>
<p class="user-email">jane.doe@example.com</p>
</div>
</div>
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have learned how to use HTML templates in JavaScript DOM to create reusable structures. By using HTML templates, you can improve the maintainability and readability of your web applications, making it easier to manage and update your code.