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.