How to use templates in Vanilla JavaScript

Akshay Garg
3 min readJul 22, 2018

--

Over the last few years, Vanilla JS (aka. plain old JavaScript) has quickly turned into one of the most popular front-end languages. A large number of frameworks and libraries are built on JavaScript.

There is one important technique that remains constant, irrespective of which framework/library you use - putting JavaScript directly into HTML. This technique is also called Templating”.

Why to put JS directly into HTML?

In a real-time environment, the data is usually fetched from an API. The fetched data can change with time and it is mostly in JSON format or an array of JavaScript objects. If the data do not bind directly into the HTML and the data changes, we might have to access DOM(Document Object Model) again and again, since it needs to be updated. This often leads to duplication of HTML code and it gets difficult to manage over time. The better approach to solve this is the use of templates.

What are templates?

A template is an HTML string, binding JavaScript data into it. It leads to the easy manipulation of DOM.

We will slowly dip our toes into the water of templates!

How it looks like?

This is a simple example of how templates are. Generally, the data comes from an array of JS objects like shown below:

In the above example, I have used string concatenation instead of string templates(ES6 feature). Both are fine. I just wanted to clear a point that both ways are ok. Throughout this article, I will be using string concatenation.

How does it manipulates the DOM?

As of now you have created a simple template, but haven’t really injected it into the DOM yet!

To inject the created template into the DOM, you will first need to get access to a DOM element to which the template could be added before or after. For that, we will use document.querySelector() like shown below:

Now we have access to the entry node of DOM. To inject template into DOM we need to decide whether to insert it before or after the entryNode. Let’s say we want to insert it before the entryNode. For that we will use insertAdjacentHTML() like:

All this knowledge can be bundled together into below piece of code:

arrayOfObjects.forEach() is used so that we don’t have to duplicate the HTML code. The final output will look like below.

Cheers! You have successfully created your own template in Vanilla JS.

On similar lines, you can use templates in various components like tables, carousels, lists, etc.

You can even refer my github repo to see how the carousel can be implemented using templates in Vanilla JS!

P.S. If you enjoyed this article, feel free to hit that clap button 👏 to help others find it. You can also share it with your friends on social media.😀 In case of any concern please leave a comment below, I’m just a comment away 😁

--

--