Search code examples
javascripthtmlweb-componenthtml5-template

Cannot get content from template


In Javascript, I am trying to dynamically create an HTML <template> element, append an <h1> element as its child, clone the template's contents, and then append the template to the document body.

The problem is when I access the content property of the template it just returns #document-fragment.

Here's the code:

var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';

var div = document.createElement('div').appendChild(h1)
temp.appendChild(div)

console.log('temp: ', temp)
console.log('temp content: ', temp.content)

var c = document.importNode(temp.content, true)
document.body.appendChild(c)

And here is the output for the console.log's:

Template output

What am I doing wrong here? Why is the template's contents showing up as empty?


Solution

  • When you create a <template>, you should append DOM content (with appendChild()) to the .content property (which is a DocumentFragment), not to the element itself.

    var temp = document.createElement('template');
    var h1 = document.createElement('h1');
    h1.textContent = 'hello';
    
    var div = document.createElement('div')
    div.appendChild(h1)
    
    //append DOM to .content
    temp.content.appendChild(div)
    
    console.log('temp: ', temp)
    console.log('temp content: ', temp.content)
    
    var c = document.importNode(temp.content, true)
    document.body.appendChild(c)

    An alternative is to add a HTML string via the innerHTML property.

    temp.innerHTML = '<div><h1>Hello</h1></div>'