Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda