javascript - appendChild() 从导入的模板中删除内容

标签 javascript dom documentfragment html5-template

我获得了 HTML5 的有效副本 <template>使用函数importNode() :

  function getTemplate() {
    var t = document.getElementById("example");
    return document.importNode(t.content,true);
  }

在此之后,我填充动态数据,

  var t = fillTemplate({
    id:"test",
    text:"Enter test data"
  });

最后,我将节点附加到目标容器中:

  var c = document.getElementById("container");
  var result = c.appendChild(t);

我的问题:result节点的所有内容都被剥离:我无法访问结果节点中模板的组件元素。实际上,result一旦 appendChild 节点根本不包含子节点操作已执行。

我期望返回值appendChild应该指向已插入到容器中并且现在是事件文档的一部分的节点。有什么解释为什么情况并非如此吗?

这是 jsfiddle(在 Chrome 53 中测试):

https://jsfiddle.net/rplantiko/mv2rbhym/

最佳答案

这是因为您操作的不是 Node 而是 DocumentFragment

如果您想获取插入的节点数量,您应该对父容器(示例中的 c)执行调用,然后您将得到正确的答案 (5)。

但是如果只想统计自己添加的子元素,就不应该使用childNodes,而应该使用ParentNode接口(interface)children的属性:

c.childNodes.length  // = 5
c.children.length    // = 2

追加到容器 c 后,DocumentFragment t 不再有子级。

来自MDN documentation :

Various other methods can take a document fragment as an argument (e.g., any Node interface methods such as Node.appendChild and Node.insertBefore), in which case the children of the fragment are appended or inserted at the location in the DOM where you insert the document fragment, not the fragment itself. The fragment itself continues to exist (in memory) but now has no children.

DOM 3 W3C recommendation也很清楚:

Furthermore, various operations -- such as inserting nodes as children of another Node -- may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.

关于javascript - appendChild() 从导入的模板中删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815979/

相关文章:

javascript - 如何获取 PeerJS 服务器中的连接用户列表(使用 express)?

javascript - 安排多个本地通知

javascript - 如何在不插入 DOM 的情况下对文本字符串使用 jQuery 选择器/find()?

javascript - 追加后如何删除文档片段中的元素

javascript - 无法更新指令模型

javascript - 如何只在启用 JS 的情况下编写 HTML 代码?

Javascript DOM 变量是引用而不是复制

java - 如何以编程方式更新元素并将其添加到 XSD

php - ajax 调用创建临时表的 php 文件

javascript - 为什么我的 appendChild 不能与 createDocumentFragment 一起使用?