Search code examples
javascriptappendchilddocumentfragment

retain reference to appended node javascript


No libraries please. Beyond my control.

I'm appending a document fragment to the dom. THIS ALL WORKS. No problemo.

How do I retain/retrieve the node list after the fragment is appended? Relevant code:

var frag = document.createDocumentFragment();
//add some content to the fragment
element.appendChild(frag);

Again, this works! I do NOT need a troubleshoot on how to add things to the dom!

If I set var e = element.appendChild(frag);, everything gets appended normally, but e = an empty document fragment.

I'm looking for some smooth magic voodoo here. Don't send me looping over the entire dom. The content could be anything, one or many nodes with or without children. If there's some trick with querySelectorAll or something that would be acceptable.

Thanks!

EDIT Upon further poking, it appears that e above is in fact a returned reference to the frag var, that is empty after appending it to the dom. It's much like the elements were neatly slid off of the fragment into the dom, and the fragment just lays around empty.


Solution

  • It's exactly what you've described; when the elements are appended to an element, they're removed from the fragment to prevent memory leaks from lingering references.

    One way to get those child nodes is to make a shallow copy of the fragment's childNodes before doing appendChild():

    // make shallow copy, use Array.prototype to get .slice() goodness
    var children = [].slice.call(frag.childNodes, 0);
    
    element.appendChild(frag);
    
    return children;