XML DOM compareDocumentPosition() Method

Definition and Usage

The compareDocumentPosition() method compares the document position of the current node with the specified node according to the document order.

This method returns a new child node.

Syntax:

elementNode.compareDocumentPostition(node)
parameter description
node Required. Specifies the node to be compared with the current node.

Example

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

The following code snippet compares the first and third <book> nodes in "books.xml":

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book')[0];
y=xmlDoc.getElementsByTagName('book')[2];
document.write(x.compareDocumentPosition(y));

The output of the above code:

4

Note:Internet Explorer will ignore the whitespace text nodes generated between nodes (such as newline characters), while Mozilla does not. Therefore, in the above example, Mozilla outputs 4, while Internet Explorer outputs 2.

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