Can I save a link to a fragment of a document?

I play with document fragment . It's hard for me to understand how it behaves when I add it to the DOM.

I create a doc fragment that I assign to a variable when I insert some things into it, and add a document fragment to the element. But if I clear the element my variable, which should refer to a document fragment, it contains an empty document fragment.

I am trying to make a cache for a third-party library that creates document fragments. So I would like this to work. Should I create a cloneNode before adding a fragment to the DOM, right?

I created a JS script: http://jsfiddle.net/4CTXG/1/

 var test = document.createDocumentFragment(); //var test = document.createElement("div"); // This one work $(test).append($("<div>").html('Hello world!')); $("#result").append(test); setTimeout(function(){ $("#result").children().remove(); $("#result").append(test); console.log('Now test should have been appended'); $(result).css({"background": "#FF0000"}); },5000) 
+6
source share
2 answers

When you add an element (e.g. <div> ) to the DOM, the element is added as a child of its new parent. Children-children are not changed. When you remove an element from its parent, the element simply detaches from the DOM. You still have a link to the Element, it will still contain its children, available for reconnection later.

When you add a DocumentFragment to the DOM, the children of the DocumentFragment are removed from the DocumentFragment and moved to the children of the parent DOM element. Now DocumentFragment is empty.

So, instead of adding a DocumentFragment, you should add a deep fragment clone.

See http://dom.spec.whatwg.org/#concept-node-insert for more details.

+11
source

Javascript objects are copied by reference, not by value. Therefore, when you assign a fragment to a variable and then insert the fragment into the DOM, the variable and the DOM refer to the same object. Any change you make to one will also occur in the other.

If you really want the variable to refer to an object other than the DOM, cloning is the right approach.

-1
source

Source: https://habr.com/ru/post/951716/


All Articles