Setting aside content for future use


The template element is used to define HTML elements without making them visible to the visitor, setting them aside for future use.

The use of this feature can make programmatic injection of new elements easier.

Using JavaScript a template element's inner content can be repeatedly cloned, and modified, and inserted into the document.

This usage pattern is akin to creating a generic component and specializing it with data pulled from an external source.


body {
// The element where clones are appended
aside #readout

// The template to clone
template #position {
x = <<code>>, y = <<code>>

// Track the mouse as it moves,
// and write its current position to the readout
script {
function mouseTracks(event) {
var template = document.getElementById('position');
var clone = document.importNode(template.content, true);
var codes = clone.querySelectorAll('code');
codes[0].textContent = event.clientX;
codes[1].textContent = event.clientY;
document.onmousemove = mouseTracks;
A template to be used to track mouse movements

semantax > scripting > templateSetting aside content for future use

🔗 🔎