Search code examples
javascripthtmldomweb-component

Difference between HTML template content and innerHTML


Say I have an HTML <template> tag that I define and select as follows:

<template>
  <h1>This is my template</h1>
</template>

let myTemplate = document.querySelector('template')

What is the difference between these properties of the template:

myTemplate.content

myTemplate.innerHTML

Solution

  • 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:

    let myTemplate = document.querySelector('template');
    
    // Method 1
    let myDiv1 = document.getElementById('div1');
    myDiv1.innerHTML = myTemplate.innerHTML;
    
    // Method 2
    let myDiv2 = document.getElementById('div2');
    myDiv2.appendChild(myTemplate.content.cloneNode(true));
    <template>
      <h3>This is my template</h3>
      <p>Hello World</p>
    </template>
    
    <div id="div1"></div>
    <hr>
    <div id="div2"></div>