Element.prototype.replaceChild
Replaces a child node within the given parent node with a new node
Syntax
element.replaceChild(newChild, oldChild)Parameters
| Parameter | Type | Description |
|---|---|---|
| newChild | Node | The new node to replace oldChild |
| oldChild | Node | The child to be replaced |
Return Value
The replaced (old) child node
Examples
const list = document.querySelector('ul')!
const newItem = document.createElement('li')
newItem.textContent = 'Replaced'
const oldItem = list.firstElementChild!
list.replaceChild(newItem, oldItem)function replaceText(parent: HTMLElement, oldText: string, newText: string) {
const walker = document.createTreeWalker(parent, NodeFilter.SHOW_TEXT)
let node: Node | null
while (node = walker.nextNode()) {
if (node.textContent === oldText) {
parent.replaceChild(document.createTextNode(newText), node)
break
}
}
}const container = document.getElementById('root')!
const old = container.children[0]
const fresh = document.createElement('section')
fresh.innerHTML = '<h2>New Section</h2>'
container.replaceChild(fresh, old)Understanding Element.prototype.replaceChild
The Element.prototype.replaceChild method in JavaScript replaces a child node within the given parent node with a new node. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.replaceChild(newChild, oldChild). It accepts 2 parameters: newChild, oldChild. When called, it returns the replaced (old) child node. Understanding when and how to use replaceChild() helps you write more expressive, readable code.
Common use cases for Element.prototype.replaceChild include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-replacewith, dom-removechild, dom-appendchild, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.replaceChild is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.replaceWithReplaces this Element in the children list of its parent with a set of Node or string objects
Element.prototype.removeChildRemoves a child node from the DOM and returns the removed node
Element.prototype.appendChildAdds a node to the end of the list of children of a specified parent node
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.