javascript - How can I convert a subtree of the DOM into a DocumentFragment? -


i'm trying "keep" subtree of dom later use , reappending based on user action (a subtree created , manipulated using documentfragment , appended dom), don't want append , hide somewhere in dom, because further (and heavy in case) manipulation on slower , incurs layout reflows , further performance impact.

is there cross-browser way (ie11+ care) convert dom subtree documentfragment? didnt' find yet searching or docs.

thank you

i'd suggest keep nodes you're interested in in array. it's more handy documentfragment, , not nasty nodelist or htmlcollection.

a little utility convert "things" documentfragments.

function fragmentflush(state){     if(state.text){         state.fragment.appendchild(document.createtextnode(state.text));         state.text = "";     }     return state.fragment; }  function fragmentiterate(state, value){     if( value instanceof node ){         fragmentflush(state).appendchild(value);     }else if(array.isarray(value)){         value.reduce(fragmentiterate, state);     }else if(value === object(value)){         fragmentiterate(state, array.from(value));     }else if(value != null){         state.text += value;     }     return state; }  function fragment(value){     return fragmentflush(fragmentiterate({         text: "",         fragment: document.createdocumentfragment()     }, value)); } 

"things" because traverses (non-cyclic) arraylike structure find nodes you've passed , builds (flattened) documentfragment that. (primitive values converted textnodes, null , undefined ignored)

var seta = [/*...*/];  var frag = fragment([     "seta: ", seta,     condition? "some more text": null,  //null values ignred     "setb: ", somenode.children,     //that's why made traverse recursively     //so can "concat" lists following line     //without having concat them     "setc: ", [seta, anotherset, /* morenodes */, andanotherset] ]);  node.appendchild(frag); 

again beware, doesn't deal cyclic references!

about 3 functions, i've extracted 1 of libs. you'd want put module , export fragment or wrap iife.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -