XML DOM Replace Nodes

Swapping and replacing XML elements

🔄 What is Replacing Nodes?

Replacing nodes means swapping one element with another in your XML document. You can replace entire elements, substitute text content, or swap child nodes. This is useful for updating XML structure while maintaining document integrity.


// Replace a child element
parent.replaceChild(newNode, oldNode);
// Create new element
var newElement = xmlDoc.createElement("tag");
                                    

Node Replacement Methods

XML DOM provides methods to replace existing nodes with new ones. You can create new elements, copy existing ones, or swap nodes entirely. Replacement maintains the document structure while updating specific parts of your XML data.

🔄

Replace Child

Swap one element for another

replaceChild()

Create Element

Make new XML elements

createElement()
📝

Create Text

Create text nodes

createTextNode()
📋

Clone Node

Copy existing elements

cloneNode()

🔹 Sample XML Data

We'll use this XML for replacement examples:

<?xml version="1.0"?>
<menu>
    <item id="1">
        <name>Coffee</name>
        <price>3.50</price>
        <category>Beverage</category>
    </item>
    <item id="2">
        <name>Old Sandwich</name>
        <price>5.00</price>
        <category>Food</category>
    </item>
</menu>

🔹 Replace a Child Element

Replace one element with a newly created element:

// Get the menu and old item
var menu = xmlDoc.getElementsByTagName("menu")[0];
var oldItem = xmlDoc.getElementsByTagName("item")[1];

// Create new item element
var newItem = xmlDoc.createElement("item");
newItem.setAttribute("id", "2");

// Create child elements
var name = xmlDoc.createElement("name");
name.appendChild(xmlDoc.createTextNode("Fresh Salad"));
var price = xmlDoc.createElement("price");
price.appendChild(xmlDoc.createTextNode("6.50"));

// Add children to new item
newItem.appendChild(name);
newItem.appendChild(price);

// Replace old with new
menu.replaceChild(newItem, oldItem);

console.log("Item replaced successfully");

Output:

Item replaced successfully

🔹 Replace Text Content

Replace the text node of an element:

// Get name element
var name = xmlDoc.getElementsByTagName("name")[0];

// Show original
console.log("Original: " + name.childNodes[0].nodeValue);

// Create new text node
var newText = xmlDoc.createTextNode("Espresso");

// Replace old text with new
name.replaceChild(newText, name.childNodes[0]);

// Show updated
console.log("Updated: " + name.childNodes[0].nodeValue);

Output:

Original: Coffee

Updated: Espresso

🔹 Clone and Replace

Clone an existing element and use it as replacement:

// Get first item
var firstItem = xmlDoc.getElementsByTagName("item")[0];

// Clone it (true = deep clone with children)
var clonedItem = firstItem.cloneNode(true);

// Modify the clone
clonedItem.setAttribute("id", "3");
var clonedName = clonedItem.getElementsByTagName("name")[0];
clonedName.childNodes[0].nodeValue = "Latte";

// Get second item and replace it
var menu = xmlDoc.getElementsByTagName("menu")[0];
var secondItem = xmlDoc.getElementsByTagName("item")[1];
menu.replaceChild(clonedItem, secondItem);

console.log("Replaced with cloned item");

Output:

Replaced with cloned item

🔹 Replace Multiple Child Elements

Replace specific child elements within a parent:

// Get first item
var item = xmlDoc.getElementsByTagName("item")[0];
var oldPrice = item.getElementsByTagName("price")[0];

// Create new price element
var newPrice = xmlDoc.createElement("price");
newPrice.setAttribute("currency", "USD");
newPrice.appendChild(xmlDoc.createTextNode("4.00"));

// Replace old price with new
item.replaceChild(newPrice, oldPrice);

// Show result
var updatedPrice = item.getElementsByTagName("price")[0];
console.log("New price: $" + updatedPrice.textContent);
console.log("Currency: " + updatedPrice.getAttribute("currency"));

Output:

New price: $4.00

Currency: USD

🔹 Create and Replace Helper Function

Create a reusable function for element replacement:

// Helper function to create element with text
function createElementWithText(doc, tagName, text) {
    var element = doc.createElement(tagName);
    element.appendChild(doc.createTextNode(text));
    return element;
}

// Get item and old name
var item = xmlDoc.getElementsByTagName("item")[0];
var oldName = item.getElementsByTagName("name")[0];

// Create new name using helper
var newName = createElementWithText(xmlDoc, "name", "Cappuccino");

// Replace
item.replaceChild(newName, oldName);

console.log("Name updated to: " + newName.textContent);

Output:

Name updated to: Cappuccino

🔹 Complete Replace Example

Full example showing element replacement:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var xmlText = `<menu>
    <item id="1">
        <name>Coffee</name>
        <price>3.50</price>
    </item>
    <item id="2">
        <name>Old Sandwich</name>
        <price>5.00</price>
    </item>
</menu>`;

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlText, "text/xml");

var menu = xmlDoc.getElementsByTagName("menu")[0];
var oldItem = xmlDoc.getElementsByTagName("item")[1];

// Show before
var oldName = oldItem.getElementsByTagName("name")[0].textContent;
var output = "BEFORE: " + oldName + "<br><br>";

// Create new item
var newItem = xmlDoc.createElement("item");
newItem.setAttribute("id", "2");

var name = xmlDoc.createElement("name");
name.appendChild(xmlDoc.createTextNode("Fresh Salad"));
var price = xmlDoc.createElement("price");
price.appendChild(xmlDoc.createTextNode("6.50"));

newItem.appendChild(name);
newItem.appendChild(price);

// Replace
menu.replaceChild(newItem, oldItem);

// Show after
var items = xmlDoc.getElementsByTagName("item");
var newName = items[1].getElementsByTagName("name")[0].textContent;
var newPrice = items[1].getElementsByTagName("price")[0].textContent;

output += "AFTER: " + newName + " - $" + newPrice;

document.getElementById("demo").innerHTML = output;
</script>

</body>
</html>

Output:

BEFORE: Old Sandwich

AFTER: Fresh Salad - $6.50

🧠 Test Your Knowledge

Which method replaces one child node with another?