XML DOM compareDocumentPosition() Method
Definition and Usage
The compareDocumentPosition() method can be used to compare the document position of the current node with a specified node according to the document order.
Syntax:
nodeObject.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 can compare the document position of the first book element with the third book element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book')[0];
var y=xmlDoc.getElementsByTagName('book')[2];
document.write(x.compareDocumentPosition(y)
);
Output:
4
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, Mozilla browsers will output 4, while Internet Explorer will output 2.
Tip:For more information about the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter.