Templates for Dynamic HTML Elements
This is probably something that already exists and is well documented, however I came across it today so I figured I would share.
It seems that more often than I'd like I'm in a situation where the user expects the ability to dynamically create new elements from a button click. Depending on if these elements already exist on the page, there's a few ways I can generate the HTML to add:
- Reference an element that exists elsewhere on the page, do a cloneNode
- Create everything via createElement and appendChild
This method, which I found while looking through the repository for Buzz* Phone for Google Chrome is a clever way to do the first option, without having to ever clear out data from a cloned node or have the requirement that it's visible on the page to users before you want them to see it.
First, define your template using <template>
1 tags, like so:
<template id="call-record-template">
<div class="w3-row call-record">
<div class="w3-col s1 call-type">
<i class="fa"></i>
</div>
<div class="w3-col s11 call-date"></div>
<div class="w3-col s1"> </div>
<div class="w3-col s11 call-display"></div>
</div>
</template>
Then in your JavaScript, do a quick cloneNode and then work with the template:
const record = document.getElementById('call-record-template').content.firstElementChild.cloneNode(true);
And there you go, no more needing the element to already be something the user can see as <template>
is set to display:none;
by default, and no more needing to painstakingly create a function that does a bunch of createElement
then combines them together.
Footnotes 🐾
This feature has been around for awhile, guess I've been under a rock. Here's the MDN page https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template↩