Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!