Replacing Elements with replaceChild
You'll learn how to swap out existing DOM elements by replacing them with new ones.
Sometimes you don't want to just remove an element or add a new one — you want to swap an old element for a completely new one in the exact same spot. This is where replacement methods come in.
The Traditional Way: replaceChild()
The replaceChild() method is called on a parent element and takes two arguments: the new element and the old element you want to replace.
const parent = document.getElementById('container');
const oldElement = document.getElementById('old-item');
const newElement = document.createElement('div');
newElement.textContent = 'I am the new element';
// Replace oldElement with newElement
parent.replaceChild(newElement, oldElement);
Notice the syntax can feel a bit backwards — you call it on the parent, not the element being replaced.
The Modern Way: replaceWith()
The newer replaceWith() method is more intuitive — you call it directly on the element you want to replace:
const oldElement = document.getElementById('old-item');
const newElement = document.createElement('div');
newElement.textContent = 'I am the new element';
// Replace directly
oldElement.replaceWith(newElement);
Analogy: Think of switching out a broken light bulb. replaceChild() is like asking the ceiling (parent) to swap bulbs for you, while replaceWith() is like the bulb replacing itself — same result, simpler instruction.
Both methods preserve the position in the DOM tree, so sibling elements stay in order.
Key Takeaway: Use replaceChild(newNode, oldNode) on the parent element or the more modern replaceWith(newNode) directly on the old element to swap DOM nodes while maintaining their position in the tree.