在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