XML DOM compareDocumentPosition() Method

Definition and Usage

compareDocumentPosition() Compare the position of two nodes in the DOM hierarchy (document).

Syntax

nodeObject.compareDocumentPosition(node)

Parameters

Parameters Description
node Required. Node object. Specifies the node to be compared with the current node.

Technical Details

DOM Version: Core Level 3 Node Object
Return value:

Numbers indicating the relative positions of the two nodes. Possible return values include:

  • 1 - No relationship, the two nodes do not belong to the same document.
  • 2 - The specified node is located before the current node.
  • 4 - The specified node follows the current node.
  • 8 - The specified node contains the current node.
  • 16 - The specified node is contained within the current node.
  • 32 - The specified node and the current node do not have a common container node, or the two nodes are different attributes of the same node.

Note:The return value can also be a combination of values. For example, a return value of 20 indicates that the specified node is contained within the current node (16) and follows the current node (4).

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 treat whitespace or new lines as text nodes, but IE 9 and earlier versions do not. Therefore, in the above example, most browsers will output 4, while IE 9 and earlier versions will output 2.

Browser Support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support

All mainstream browsers support the compareDocumentPosition() method.

Note:Internet Explorer 9 and earlier versions do not support this method.