Say I have an HTML <template>
tag that I define and select as follows:
JavaScript
x
6
1
<template>
2
<h1>This is my template</h1>
3
</template>
4
5
let myTemplate = document.querySelector('template')
6
What is the difference between these properties of the template:
JavaScript
1
4
1
myTemplate.content
2
3
myTemplate.innerHTML
4
Advertisement
Answer
Contrary to innerHTML
, content
returns a document fragment, and so you get immediate access to the DOM without an intermediate conversion to and from a string.
Here is the difference in use:
JavaScript
1
9
1
let myTemplate = document.querySelector('template');
2
3
// Method 1
4
let myDiv1 = document.getElementById('div1');
5
myDiv1.innerHTML = myTemplate.innerHTML;
6
7
// Method 2
8
let myDiv2 = document.getElementById('div2');
9
myDiv2.appendChild(myTemplate.content.cloneNode(true));
JavaScript
1
8
1
<template>
2
<h3>This is my template</h3>
3
<p>Hello World</p>
4
</template>
5
6
<div id="div1"></div>
7
<hr>
8
<div id="div2"></div>