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

165
Visualizações
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 Respostas
Responde à pergunta

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