Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Last active November 2, 2019 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciopaiva/8657a2bd0c9b0b019c8d2daa8cbdbba6 to your computer and use it in GitHub Desktop.
Save luciopaiva/8657a2bd0c9b0b019c8d2daa8cbdbba6 to your computer and use it in GitHub Desktop.

Using HTML templates in Javascript

This is the proper way to have HTML templates and clone them in Javascript.

First add the template to your HTML:

<template id="example-template">
    <div class="example">
        <p>Hello</p>
        <p>World</p>
    </div>
</template>

Then get a reference to the template element during JS startup:

const template = document.getElementById("example-template").content.querySelector(".example");

Notice that <template> is just used as way to properly hide the element used as the actual template. It has no other real need to be here. You could even get rid of <template> altogether and add a hidden CSS class to example, but then you'd have to remember to remove that class from the resulting element after it is cloned (I prefer the <template> solution).

Once the template is ready, you can then clone as much as you like:

const element = template.cloneNode(true);
element.setAttribute("id", "my-newly-created-element");
document.body.appendChild(element);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment