Remove and replace elements
Quick answer
remove detaches an element from its parent. A JavaScript variable can still refer to the detached node. replaceChildren replaces all children with supplied nodes or strings.
Browser example
Run in a browser document, not a bare Node.js process.
const r=document.createElement("div"),p=document.createElement("p");p.textContent="old";r.append(p);p.remove();r.replaceChildren("new");console.log(p.textContent,r.textContent,p.parentNode===null);Expected console output:
old new trueCommon mistake
Removing a node does not guarantee immediate garbage collection.
Practice
Remove an item, then insert it again using its retained reference.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Remove and replace elements — Knowledge Check
Check the central concept, apply it to a new scenario, and predict browser behavior.
Can a retained reference still access a removed element?
What does a call to replaceChildren with no arguments do?
After removing an element, what can you do with a retained variable referring to it?
Which claim about garbage collection after remove is justified?
What is printed by this browser snippet? (Remove and replace elements)
const p=document.createElement("div");const a=document.createElement("span");p.append(a);p.replaceChildren("new");console.log(p.children.length,a.parentNode===null);