XML DOM removeChild() method

Node object reference manual

Definition and usage

The removeChild() method can delete a node from the child node list.

If the deletion is successful, this method can return the deleted node, or return NULL if it fails.

Syntax:

nodeObject.removeChild(node)
Parameter Description
node Required. Specify the node to be deleted.

Prompt and note

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 following example, we will use a function to check the node type of the last child node.

The node type of the element node is 1, so if the first child node is not an element node, it will move to the next node and continue to check whether this node is an element node. The entire process will continue until the first element child node is found. By this method, we can get the correct method in Internet Explorer and Mozilla.

Prompt:For more information on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM browser chapters.

examples

In all examples, we will use the XML file books.xml, and JavaScript functions loadXMLDoc().

The following code snippet can be used to remove the last child node from the first <book> element:

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

Output:

Node removed: price

Node object reference manual