XML DOM Remove Nodes
Removing parts of a document — an out-of-stock product, a private field before sharing a file, an obsolete attribute — is a common job. The DOM offers both an older parent-based method and a simpler modern one.
Removing an element
| Method | Called on | Returns |
|---|---|---|
parent.removeChild(child) |
The parent | The removed node |
child.remove() |
The node itself | undefined |
<!DOCTYPE html>
<html>
<body>
<script>
const xml = '<library><book id="b1">The Hobbit</book><book id="b2">A Brief History of Time</book><book id="b3">Cien años de soledad</book></library>';
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const lib = xmlDoc.documentElement;
// Classic way: ask the parent
const removed = lib.removeChild(xmlDoc.querySelector('[id="b2"]'));
console.log('Removed:', removed.textContent);
// Modern way: the node removes itself
xmlDoc.querySelector('[id="b3"]').remove();
console.log(new XMLSerializer().serializeToString(xmlDoc));
</script>
</body>
</html>A removed node isn't destroyed — it still exists in memory and can be inserted somewhere else, as long as you keep a reference to it (like removed above).
If you only have the node, node.parentNode.removeChild(node) was the traditional idiom; node.remove() does the same with less typing.
Removing several elements
Use a static list (querySelectorAll) so removals don't disturb the loop:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<inbox>
<message spam="no"><subject>Team lunch</subject></message>
<message spam="yes"><subject>You won a prize!!!</subject></message>
<message spam="no"><subject>Invoice #2231</subject></message>
<message spam="yes"><subject>Cheap watches</subject></message>
</inbox>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const spam = xmlDoc.querySelectorAll('message[spam="yes"]');
spam.forEach(m => m.remove());
console.log(`Removed ${spam.length} spam messages`);
console.log('Left:', [...xmlDoc.querySelectorAll('subject')].map(s => s.textContent).join(', '));
</script>
</body>
</html>Removing text and attributes
| Goal | Code |
|---|---|
| Empty an element | el.textContent = '' or el.replaceChildren() |
| Remove one text node | textNode.remove() |
| Remove an attribute by name | el.removeAttribute('name') |
| Remove an attribute node | el.removeAttributeNode(attrNode) |
| Remove all whitespace-only text nodes | walk the tree and remove them (below) |
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<customer id="c9" internalScore="87" createdBy="admin">
<name>Rui Costa</name>
<password>hunter2</password>
<email>rui@example.com</email>
</customer>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const c = xmlDoc.documentElement;
// Strip private data before sharing
c.removeAttribute('internalScore');
c.removeAttribute('createdBy');
c.querySelector('password').remove();
// Clean up whitespace-only text nodes so the output is compact
function stripBlank(node) {
for (const child of [...node.childNodes]) {
if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() === '') child.remove();
else stripBlank(child);
}
}
stripBlank(c);
console.log(new XMLSerializer().serializeToString(xmlDoc));
</script>
</body>
</html>Note: You can't remove the root element and leave a valid document behind — an XML document needs exactly one root. Replace it instead if you must.
Test yourself
Which call removes node from its parent?
node.delete()node.remove()xmlDoc.remove(node)node.parentNode.remove(node)
What does removeChild() return?
trueorfalse- The parent
- The removed node
- Nothing
How do you delete the genre attribute of book?
book.genre = nullbook.setAttribute('genre', null)book.removeAttribute('genre')book.attributes.genre.remove()