XML DOM Replace Nodes
Replacing swaps one node for another at the same position in the tree. It is how you substitute a whole record, rename an element, or swap text for markup.
replaceChild() and replaceWith()
| Method | Called on | Notes |
|---|---|---|
parent.replaceChild(newNode, oldNode) |
The parent | Returns the old node. Note the order: new first |
oldNode.replaceWith(newNode, …) |
The old node | Modern; accepts several nodes or strings |
<!DOCTYPE html>
<html>
<body>
<script>
const xml = '<library><book id="b1"><title>The Hobbit</title></book><book id="b2"><title>Old Edition</title></book></library>';
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
// Build the replacement element
const fresh = xmlDoc.createElement('book');
fresh.setAttribute('id', 'b2');
const t = xmlDoc.createElement('title');
t.textContent = 'A Brief History of Time';
fresh.appendChild(t);
const old = xmlDoc.querySelector('[id="b2"]');
const returned = xmlDoc.documentElement.replaceChild(fresh, old);
console.log('Replaced:', returned.textContent);
console.log(new XMLSerializer().serializeToString(xmlDoc));
</script>
</body>
</html>Replacing text
To change text you can just assign textContent (previous lesson). Replacing text nodes is useful with mixed content — for example turning a plain word into markup:
<!DOCTYPE html>
<html>
<body>
<script>
const xmlDoc = new DOMParser().parseFromString(
'<para>Read the manual before use.</para>', 'application/xml');
const textNode = xmlDoc.documentElement.firstChild;
// Split "Read the manual before use." around the word "manual"
const [before, after] = textNode.nodeValue.split('manual');
const link = xmlDoc.createElement('link');
link.setAttribute('href', 'manual.pdf');
link.textContent = 'manual';
textNode.replaceWith(before, link, after); // strings become text nodes
console.log(new XMLSerializer().serializeToString(xmlDoc));
</script>
</body>
</html>Renaming an element
tagName can't be changed, so renaming means: create an element with the new name, copy the attributes, move the children, then replace.
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<catalog>
<item id="p1" lang="en"><name>Desk lamp</name><price>29</price></item>
<item id="p2" lang="en"><name>Bookend</name><price>12</price></item>
</catalog>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
function rename(el, newName) {
const copy = el.ownerDocument.createElement(newName);
for (const a of el.attributes) copy.setAttribute(a.name, a.value);
while (el.firstChild) copy.appendChild(el.firstChild); // moves, doesn't copy
el.replaceWith(copy);
return copy;
}
for (const item of [...xmlDoc.querySelectorAll('item')]) rename(item, 'product');
console.log(new XMLSerializer().serializeToString(xmlDoc));
</script>
</body>
</html>appendChild moves a node that is already in the tree, which is why the while (el.firstChild) loop ends: each iteration takes the first child away from el.
Replacing attribute values
Attributes are "replaced" simply by setting them again with setAttribute. There's also replaceChildren() for elements, which removes all children and inserts the given nodes in one call:
xmlDoc.querySelector('title').replaceChildren('New title'); // same effect as textContent = ...Tip: Build the new node completely before inserting it. Each insertion into a large document can trigger work (and, in an HTML page, a repaint), so it's cheaper to assemble a subtree off-document and attach it once.
Test yourself
What is the correct argument order for replaceChild?
replaceChild(oldNode, newNode)replaceChild(newNode, oldNode)replaceChild(parent, newNode)- Either order works
How do you rename <item> to <product>?
item.tagName = 'product'item.rename('product')- Create a
productelement, move attributes and children, then replace item.nodeName = 'product'