Skip to content

XML DOM: Remove Nodes

How to delete element nodes, text nodes, and attributes in XML using DOM methods like removeChild(), removeAttribute(), and removeAttributeNode() with practical JavaScript examples.

Let's see how to remove an element node with removeChild(), a text node, an attribute node by name and by object with removeAttribute() and removeAttributeNode().

Remove an Element Node with removeChild() Method

The removeChild() method removes a specified node. When a node is removed, all its child nodes are also removed.

Example:

y = xmlDoc.getElementsByTagName("book")[0];  
xmlDoc.documentElement.removeChild(y);

Remove the Current Node

The removeChild() method is the only way to remove a specified node.

When you have navigated to the node you want to remove, it is possible to remove that node using the parentNode property and the removeChild() method.

x = xmlDoc.getElementsByTagName("tagname")[0];  
x.parentNode.removeChild(x);

Remove a Text Node with removeChild() Method

The removeChild() method can also be used to remove a text node.

x = xmlDoc.getElementsByTagName("tagname")[0];  
y = x.childNodes[0];  
x.removeChild(y);

Clear a Text Node with nodeValue

The nodeValue property can be used to change the value of a text node.

xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "";

Remove Attribute Node by Name with removeAttribute()

The removeAttribute() method removes the attribute with the specified name from the element.

The syntax is:

element.removeAttribute(attrName);

where attrName is a string that specifies the name of the attribute to remove from the element.

Example: remove the publisher attribute in the first <book> element:

x = xmlDoc.getElementsByTagName("book");  
x[0].removeAttribute("publisher");

Remove Attribute Node by Object with removeAttributeNode()

The removeAttributeNode() removes the specified attribute from the element.

The syntax is:

let removedNode = element.removeAttribute(attrName);

where attributeNode is the attribute node to remove from the element.

Example: remove all attributes of first <book> element:

x = xmlDoc.getElementsByTagName("book")[0];
while (x.attributes.length > 0) {  
	attNode = x.attributes[0];  
	old_att = x.removeAttributeNode(attNode);  
}
Navigation