How to Replace Element in JavaScript: Simple Guide
To replace an element in JavaScript, use the
replaceChild method on the parent node or set the element's outerHTML property to new HTML. Both methods let you swap an existing element with a new one easily.Syntax
There are two common ways to replace an element in JavaScript:
- Using
replaceChild: Replace a child node with a new node on the parent element. - Using
outerHTML: Replace the entire element by setting its HTML content.
javascript
parentNode.replaceChild(newElement, oldElement);
oldElement.outerHTML = '<div>New content</div>';Example
This example shows how to replace a paragraph element with a new one using both replaceChild and outerHTML.
javascript
const oldPara = document.getElementById('old'); // Using replaceChild const newPara = document.createElement('p'); newPara.textContent = 'This is the new paragraph using replaceChild.'; oldPara.parentNode.replaceChild(newPara, oldPara); // Using outerHTML (uncomment to test separately) // const oldPara2 = document.getElementById('old2'); // oldPara2.outerHTML = '<p>This is the new paragraph using outerHTML.</p>';
Common Pitfalls
Common mistakes when replacing elements include:
- Trying to call
replaceChildon the element itself instead of its parent. - Using
outerHTMLon elements that are not in the DOM, which won't update the page. - Not creating a new element properly before replacing.
javascript
// Wrong: calling replaceChild on the element itself const oldElem = document.getElementById('old'); const newElem = document.createElement('div'); newElem.textContent = 'New'; // oldElem.replaceChild(newElem, oldElem); // Error: replaceChild is not a function on element itself // Right: call replaceChild on parent oldElem.parentNode.replaceChild(newElem, oldElem);
Quick Reference
| Method | Description | Usage |
|---|---|---|
| replaceChild | Replaces a child node with a new node | parentNode.replaceChild(newNode, oldNode) |
| outerHTML | Replaces the element's HTML content | element.outerHTML = ' |
Key Takeaways
Use parentNode.replaceChild(newElement, oldElement) to replace elements safely.
Setting element.outerHTML replaces the entire element with new HTML.
Always call replaceChild on the parent node, not the element itself.
Create new elements properly before replacing old ones.
outerHTML replacement updates the DOM immediately but replaces the whole element.