In Javascript, I am trying to dynamically create an HTML element, append an element as its child, clone the template\'s
Note, var div = document.createElement('div').appendChild(h1) sets div variable to h1, the appended element, not div element; see What is the behavior of document.createElement when passed as an argument?.
Set .innerHTML of <template> to .outerHTML of div element, call .appendChild() chained to document.body with temp.content as parameter.
window.onload = function() {
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div');
div.appendChild(h1);
temp.innerHTML = div.outerHTML;
console.log('temp: ', temp.content);
document.body.appendChild(temp.content);
}
<body></body>
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>'