HTML DOM Element replaceChild()
Example
Replace a text node in an <li> element with a new text node:
const newNode = document.createTextNode("Water");
const element = document.getElementById("myList").children[0];
element.replaceChild(newNode, element.childNodes[0]);
Definition and Usage
The replaceChild()
method replaces a child node with a new node.
Syntax
node.replaceChild(newnode, oldnode)
Parameters
Parameter | Description |
newnode | Required. The node to insert. |
oldnode | Required. The node to remove. |
Return Value
Type | Description |
Node | The replaced node. |
More Examples
Example
Replace an <li> element with a new <li> element:
// Create a new <li> element:
const element = document.createElement("li");
// Create a new text node:
const textNode = document.createTextNode("Water");
// Append the text node to the <li> element:
element.appendChild(textNode);
// Get the <ul> element with id="myList":
const list = document.getElementById("myList");
// Replace the first child node with the new <li> element:
list.replaceChild(element, list.childNodes[0]);
Before:
- Coffee
- Tea
- Milk
After:
- Water
- Tea
- Milk
Browser Support
element.replaceChild()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |