CameronB
CameronB

Reputation: 103

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);

Upvotes: 1

Views: 948

Answers (2)

Hiren
Hiren

Reputation: 621

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

Upvotes: 4

Chris.Z
Chris.Z

Reputation: 71

If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. The return value of Node.appendChild() is the same thing with the document fragment which is empty.

I think you can put the children of document fragment into another container (e.g. an array). Those children are the real DOM refernces which are inserted.

    const df = new DocumentFragment();
    const t1 = document.createElement('template1');
    t1.innerHTML = '<span>Test1</span>';
    t1.id = "xxx"
    const t2 = document.createElement('template2');
    t2.innerHTML = '<span>Test2</span>';
    df.appendChild(t1);
    df.appendChild(t2);
    document.body.appendChild(df);
    window.alert(document.getElementById('xxx') === t1);

Upvotes: 0

Related Questions