Skip to content
Advertisement

How to get actual element from document fragment?

I have a template like so:

JavaScript

That I convert to document fragment like so:

JavaScript

And then I add this element with append:

JavaScript

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

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