javascriptappendchilddocumentfragment

How to get the DOM reference to an inserted document fragment


I am attempting to get the DOM reference of an inserted document fragment in vanilla Javascript. I'm currently using Node.appendChild() however the returned reference is the document fragment as outlined here: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild#return_value

Is there any approach I could use to get the inserted DOM reference?

I did find the following Stack Overflow answer for a similar question but not related directly to document fragments, this solution uses either CSS animations or Mutation Observers but seems overkill for what I'm attempting. https://stackoverflow.com/a/38636244/13306195

const temp = document.createElement('template');
temp.innerHTML = '<span>Test</span>';
const neededReference = document.body.appendChild(temp.content);

Solution

  • The thing about document fragments is that you have to clone their content whenever appending them to the DOM in order to make them as DOM Nodes and not just the fragments.

    const temp = document.createElement('template');
    temp.innerHTML = '<span>Test</span>';
    const neededReference = 
       document.body.appendChild(
          temp.content.cloneNode(true).firstElementChild
       );
    console.log(neededReference); // should give the reference to span element