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]);
The replaceChild()
method replaces a child node with a new node.
node.replaceChild(
newnode,
oldnode)
Parameter | Description |
newnode | Required. The node to insert. |
oldnode | Required. The node to remove. |
Type | Description |
Node | The replaced node. |
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:
After:
element.replaceChild()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!