通过原始 DOM 引用元素查找克隆元素

问题描述

我有一个包含多个子元素的 <template>。我是 cloning these child elements via .cloneNode(true) 并将它们附加到 document.head

<template id="my_template">
    <script>
    // …
    </script>
</template>
var template=document.getElementById('my_template');
document.head.appendChild(template.content.cloneNode(true));

我想要的

有没有办法在任何给定时刻判断 document.head 是否已经包含 <template> 内容

我尝试了什么

  • 维护旗帜,例如template.setAttribute('data-cloned',1) 有效,但它是一种解决方法
  • document.head.contains() 不起作用可能是因为克隆的元素在内部是不同的:
    for (var i=0; i<template.content.children.length; i++) {
        document.head.contains(template.content.children[i]); // always false
    }
    
  • 针对 document.head 中的每个元素循环遍历每个模板元素,并使用 .is() 或它们的 .outerHTML 比较它们似乎不是很有效。

我现在正在使用 flag 属性,但很想知道是否有一种方法可以通过仅使用模板内容document.head 而不创建属性或 className 混乱和/或额外修改来完成此操作他们。只要可能且合理,我想避免依赖 jQuery。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)