简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM