Home > Software design >  removeChild does not work in a setTimeout if there is one element
removeChild does not work in a setTimeout if there is one element

Time:04-09

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?

CodePudding user response:

Since firstChild Node bight well be a #text Node

Either use .firstElementChild or rather simply: p.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>

  • Related