WebComponents:删除克隆的模板

WebComponents: Remove cloned template

我正在使用 webcomponentsjs polyfill。没有 x-tag、polymer 等。最好是 vanilla JS。

克隆模板并将其附加到文档后,我无法再次删除它,因为它缺少父节点。

var tmpl = document.getElementById('tmpl');
var clone = document.importNode(tmpl.content, true);
document.body.appendChild(clone);
console.log(clone.parentNode); // parentNode is null (not undefined!)
clone.parentNode.removeChild(clone); // fails!

You may see yourself in this jsbin

我的问题是:如何再次删除该元素。我错过了什么吗?

你搞混了DocumentFragment vs. Nodetemplatecontent 显然是 DocumentFragment:

的一个实例
<template>
  <div>node 1</div>
  <p>node 2</p>
  etc
</template>

根据documentationNode#appendChild接受文档片段:

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, not the fragment itself.

那么,您希望文档片段的父级是什么?它显然是空的,因为实体“文档片段”在这个上下文中是虚拟的。所以,要实现你想要的,你首先要创建一个容器,然后将节点附加到它/清理它的内容。

<body>
  ...
  <div id='container'></div>
  ...
</body>

添加涉及 ShadowDOM 的模板内容的常用方法:

var shadow = document.querySelector('#container').createShadowRoot();
shadow.appendChild(document.querySelector('#tmpl').content, true);

或者不使用 ShadowDOM,按原样插入:

document.querySelector('#container').appendChild(
  document.querySelector('#tmpl').content, true
);

希望对您有所帮助。