Dom Replace Nodes in XML
DOM Replace Nodes in XML
Replacing a node in an XML DOM means swapping an existing node with a new one.
Key Method:
parentNode.replaceChild(newNode, oldNode)
The method replaces
oldNodewithnewNodeinside theparentNode.The replaced node is removed from the DOM.
newNodemust be a node created or imported into the document.
Example XML
<library> <book id="101"> <title>Effective Java</title> </book> <book id="102"> <title>Clean Code</title> </book></library>Replace Node Using JavaScript DOM
// Assume xmlDoc is the parsed XML documentconst library = xmlDoc.getElementsByTagName("library")[0];// Old node to replaceconst oldBook = library.getElementsByTagName("book")[0];// Create a new <book> elementconst newBook = xmlDoc.createElement("book");newBook.setAttribute("id", "103");const newTitle = xmlDoc.createElement("title");newTitle.textContent = "JavaScript: The Good Parts";newBook.appendChild(newTitle);// Replace old book with new booklibrary.replaceChild(newBook, oldBook);Notes:
The
replaceChildmethod returns the replaced node (the one removed).You must call
replaceChildon the parent node of the node you want to replace.newNodecan be created using methods likecreateElement,createTextNode, etc.
Summary
| Operation | Method |
|---|---|
| Replace a node | parentNode.replaceChild(newNode, oldNode) |
If you want, I can provide a runnable example or help with XML manipulation tasks!