2017-04-20 113 views
1

在Javascript中,我试图动态创建一个HTML <template>元素,附加一个<h1>元素作为其子元素,克隆模板的内容,然后将模板附加到文档主体。无法从模板获取内容

问题是当我访问模板的content属性时,它只返回#document-fragment

下面的代码:

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) 

这里是为console.log's输出:

Template output

什么我错在这里做什么?为什么模板的内容显示为空?

+2

由于appendChild函数返回子元素('h1')而不是父元素('div'),因此'div'被“剥离”。 – Titus

+0

@Titus啊好的。我以为我将孩子追加到'div',然后'div'被返回。感谢您指出了这一点。 – Graham

回答

2

当你创建一个<template>,你应该追加DOM内容(与appendChild())至.content财产(这是一个DocumentFragment的),而不是元素本身。

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)

一种替代方法是通过innerHTML属性添加一个HTML字符串。

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

注意,var div = document.createElement('div').appendChild(h1)设置div变量为h1,附加元素,而不是div元素;见What is the behavior of document.createElement when passed as an argument?

<template>.innerHTML至元素.outerHTMLdiv,叫.appendChild()document.bodytemp.content作为参数。

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>