无法从模板中获取内容

Cannot get content from template

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

问题是当我访问模板的 content 属性 时,它只是 returns #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 的输出:

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

注意,var div = document.createElement('div').appendChild(h1)div 变量设置为 h1 附加元素,而不是 div 元素;参见

<template>.innerHTML 设置为 div 元素的 .outerHTML,使用 temp.content 调用链接到 document.body.appendChild()作为参数。

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>

当您创建 <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>'