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
removeChild does not work in a setTimeout if there is one element

Here is the code in question:

        var p = document.createElement("p");
        holder.appendChild(p);
        setTimeout(function(){
            if (holder.firstChild != null){
                holder.removeChild(holder.firstChild);
            }
        },500);

So the expected functionality is that the p goes into the holder, and in 500ms it gets removed. Yet the p element stays forever, even though I can confirm that the element is not null. What's going on?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since firstChild Node bight well be a #text Node

Either use .firstElementChild or rather simply: p.remove()

  • firstChild
  • firstElementChild
  • .append()
  • .remove()

Example:

// DOM utility functions:

const find = (sel, parent) => (parent ||document).querySelector(sel);
const create = (tag, props) => Object.assign(document.createElement(tag), props);

// Task:

const elHolder = find("#holder");
const elP = create("p", {textContent: "I will get removed soon!"});

elHolder.append(elP);
setTimeout(() => {
  elP.remove();
}, 1000);
<div id="holder"></div>

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