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

Time:11-13

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.

CodePudding user response:

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...

CodePudding user response:

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
  • Related