Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda