简体   繁体   中英

How to add/remove children from DocumentFragment after it has inserted into parent?

I'm trying to use DocumentFragment as an insertion point of other elements something like this:

const parent = document.createElement('div');
const container = document.createDocumentFragment();
parent.appendChild(container);

// the following code should produce <div><p></p></div>
const child = document.createElement('p');
container.appendChild(child);

// when the following code execute it should produce <div></div>
container.removeChild(child);

The main problem is it does not work. Any elements inserted into container after it was inserted into parent does not get rendered in parent . My goal is I want container to act like a transparent parent to its children so CSS selector will see its children as a children of parent .

That's not how appendChild works with documentFragment. Using appendChild of a document fragment appends the fragments children, not the fragment itself.

See Dom Standard - 4.2.3. Mutation algorithms - "To insert a node into a parent...

It seems you cannot accomplish this using DocumentFragment . See Mozilla MDN :

A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM […] Doing this moves the fragment's nodes into the DOM, leaving behind an empty DocumentFragment .

You can check this behaviour using the console:

> const container = document.createDocumentFragment();
> container.appendChild(document.createElement('span'));
> container // contains the span element
▼ #document-fragment
    <span>​</span>​
> const parent = document.createElement('div');
> parent.appendChild(container);
> parent
▼ <div>
    ​<span>​</span>
  ​</div>​
> container // is now empty
    #document-fragment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM