XML DOM compareDocumentPosition() Method

Definition and Usage

compareDocumentPosition() This method compares the document position of the current node with the specified node based on the document order.

Syntax

elementNode.compareDocumentPostition(node)
Parameter Description
node Required. Specifies the node to be compared with the current node.

Example

The following code loads "books.xml" into xmlDoc and compares the positions of two nodes (the first and third <book> elements) in the DOM hierarchy:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   {}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName('book')[0];
    var y = xmlDoc.getElementsByTagName('book')[2];
    document.getElementById("demo").innerHTML =
    x.compareDocumentPosition(y);
{}

Try It Yourself

Most browsers will treat whitespace or new lines as text nodes, while IE 9 and earlier versions will not. Therefore, in the above example, most browsers will output 4, while IE 9 and earlier versions will output 2.

For more information on the differences between browsers, please visit the DOM Browser section in the XML DOM tutorial.