In Javascript, I am trying to dynamically create an HTML element, append an
element as its child, clone the template\'s
When you create a , 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 = 'Hello
'