2017-04-20 116 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>