revision:
The replaceChild() method of the Node interface replaces a child node within the given (parent) node with a new node.
node.replaceChild(newChild, oldChild) node.replaceChild(newNode, oldNode)
Parameters:
newChild, newNode : required; the new node to replace oldChild. The node to insert.
oldChild, oldNode : required; the child to be replaced. The node to be removed.
// Create an empty element node without an ID, any attributes, or any content const sp1 = document.createElement("span"); sp1.id = "newSpan"; const sp1_content = document.createTextNode("new replacement span element."); // Apply that content to the new element sp1.appendChild(sp1_content); // Build a reference to the existing node to be replaced const sp2 = document.getElementById("childSpan"); const parentDiv = sp2.parentNode; // Replace existing node sp2 with the new span element sp1 parentDiv.replaceChild(sp1, sp2);
Click "Replace" to replace the first item in the the list.
This example replaces the Text node "Coffee" with a Text node "Water". Replacing the entire li element is also an alternative.
<div> <ul id="myList-A"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <p>Click "Replace" to replace the first item in the the list.</p> <button onclick="newNodeA()">"Replace"</button> <p>This example replaces the Text node "Coffee" with a Text node "Water". Replacing the entire li element is also an alternative.</p> </div> <script> function newNodeA() { // Select first child element: const element = document.getElementById("myList-A").children[0]; // Create a new text node: const newNode = document.createTextNode("Water"); // Replace the text node: element.replaceChild(newNode, element.childNodes[0]); } </script>
Click the button to replace the first item in the the list.
<div> <ul id="myList1"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <p>Click the button to replace the first item in the the list.</p> <button onclick="newNode1()">Try it</button> </div> <script> function newNode1() { const element = document.createElement("li"); const textNode = document.createTextNode("Beer"); element.appendChild(textNode); const list = document.getElementById("myList1"); list.replaceChild(element, list.children[0]); } </script>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<div> <div id="app"> <h4>Lorem ipsum</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> <script> var el = document.getElementById("app"); var oldNode = el.getElementsByTagName("h4")[0]; var newNode = document.createElement("h4"); var newNodeContent = document.createTextNode("New Lorem ipsum"); newNode.appendChild(newNodeContent); el.replaceChild(newNode, oldNode); </script>