XML DOM removeChild() method

Definition and Usage

The removeChild() method deletes a child node.

If successful, returns the deleted node, otherwise returns NULL.

Syntax:

elementNode.removeChild(node)
Parameter Description
node Required. Specifies the child node to be deleted.

Example

In all examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().

The following code snippet deletes the last child node of the first <book> element:

//check if last child node is an element node
function get_lastchild(n)
{
x=n.lastChild;
while (x.nodeType!=1)
  {
  x=x.previousSibling;
  }
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
deleted_node=x.removeChild(get_lastchild(x));
document.write("Node removed: " + deleted_node.nodeName);

Output:

Node removed: price

Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the above example, we created a function to get the correct child element.

Tip:For more information about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com DOM browser This section.