Skip to content
Advertisement

How to get actual element from document fragment?

I have a template like so:

<template id="my-template">
   <div></div>
</template>

That I convert to document fragment like so:

const elementFragment = document.getElementById("my-template").content.cloneNode(true);

And then I add this element with append:

document.body.append(elementFragment);

Now the issue is that I need a reference to the appended element, but the reference I have is only a Dogument-Fragment instead of being a HTLMDivElement.

How can I get the actual DOM element?

Advertisement

Answer

From MDN: use firstElementChild to get the first (and in this case only) child of the template, which is an actual Element node.

const elementFragment = document.getElementById("my-template").content.firstElementChild.cloneNode(true);
                                                                      ^^^^^^^^^^^^^^^^^^

If your template consists of multiple elements, you’ll need to wrap them in a <div> or other container element.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement