Cloning and Using Templates
📅
The content.cloneNode() Method
The primary way to activate templates is cloning:
const template = document.getElementById('my-template');
const clone = template.content.cloneNode(true); // true = deep clone
document.body.appendChild(clone);
The deep Parameter
cloneNode(true)— copy with all descendantscloneNode(false)— copy only the element itself
Usage Examples
Basic Cloning
<template id="button-template">
<button class="btn">Button</button>
</template>
<script>
const template = document.getElementById('button-template');
const clone = template.content.cloneNode(true);
document.getElementById('container').appendChild(clone);
</script>
Multiple Instances
// Create multiple copies
for (let i = 0; i < 5; i++) {
const clone = template.content.cloneNode(true);
document.body.appendChild(clone);
}
Activation Behavior
When cloning templates:
- ✅ Scripts start executing
- ✅ Images load
- ✅ Styles apply
- ✅ Elements become part of DOM
Performance Tips
// Better: cloning from existing template
const clone = template.content.cloneNode(true);
// Worse: creating via innerHTML (slower)
element.innerHTML = '<div>New element</div>';