问题
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
:
What am I doing wrong here? Why is the template's contents showing up as empty?
回答1:
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>'
回答2:
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>
来源:https://stackoverflow.com/questions/43508177/cannot-get-content-from-template