0

I have a <template> with several child elements in it. I'm cloning these child elements via .cloneNode(true) and appending them to document.head.

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

What I want

Is there a way to tell at any given moment whether document.head already contains the <template> contents?

What I tried

  • Maintaining a flag e.g. template.setAttribute('data-cloned', 1) works, but is a workaround
  • document.head.contains() doesn't work probably because a cloned element is internally different:
    for (var i=0; i<template.content.children.length; i++) {
        document.head.contains(template.content.children[i]); // always false
    }
    
  • looping through every template element against every element inside document.head, and comparing them using .is(), or their .outerHTML doesn't seem to be very effective.

I'm using the flag attribute right now, but am curious to see if there is a way to accomplish this by only using the template contents and the document.head without creating attribute or className clutter and/or additionally modifying them. I would like to avoid relying on jQuery as long as it's possible and reasonable.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
  • There's nothing that links an element and its clones. – Barmar Apr 01 '21 at 11:12
  • Add a unique class to an element in the template. Then use `document.head.querySelector(".thatclass")` – Barmar Apr 01 '21 at 11:13
  • @Barmar thank you for the suggestion, I updated the question. I'm curious to know if this is doable without any additional classes or attributes. If not, I'll just stick with the template flag attribute – ᴍᴇʜᴏᴠ Apr 01 '21 at 11:16
  • I'm pretty sure there's nothing built-in that will do this. – Barmar Apr 01 '21 at 11:17
  • you could use IDs to identify them and CLASSes to group them ... and for short cuts you can use local storage to store them ... – helle Apr 01 '21 at 11:28

0 Answers0