在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
輸出:
什麼我錯在這裏做什麼?爲什麼模板的內容顯示爲空?
由於appendChild函數返回子元素('h1')而不是父元素('div'),因此'div'被「剝離」。 – Titus
@Titus啊好的。我以爲我將孩子追加到'div',然後'div'被返回。感謝您指出了這一點。 – Graham