I have a template like so:
JavaScript
x
4
1
<template id="my-template">
2
<div></div>
3
</template>
4
That I convert to document fragment like so:
JavaScript
1
2
1
const elementFragment = document.getElementById("my-template").content.cloneNode(true);
2
And then I add this element with append:
JavaScript
1
2
1
document.body.append(elementFragment);
2
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.
JavaScript
1
3
1
const elementFragment = document.getElementById("my-template").content.firstElementChild.cloneNode(true);
2
^^^^^^^^^^^^^^^^^^
3
If your template consists of multiple elements, you’ll need to wrap them in a <div>
or other container element.