THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

XML DOM compareDocumentPosition() Method


Node Object Reference Node Object

Example

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

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
��� if (xhttp.readyState == 4 && xhttp.status == 200) {
������� myFunction(xhttp);
��� }
};
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);
}

The output of the code above will be:

4
Try it yourself »

Most browsers, will treat empty white-spaces or new lines as text nodes, IE 9 and earlier will not. So, in the example above, most browsers will output 4, while IE 9 and earlier will output 2.


Definition and Usage

The compareDocumentPosition() method compares the placement of two nodes in the DOM hierarchy (document).


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The compareDocumentPosition() method is supported in all major browsers.

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


Syntax

nodeObject.compareDocumentPosition(node)

Parameters

Parameter Type Description
node Node object Required. Specifies the node to compare with the current node

Return Value

Type Description
Number A Number representing where the two nodes are positioned compared to each other. The possible return values are:

1 - No relationship, the two nodes do not belong to the same document.

2 - The specified node precedes 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 by the current node.

32 - The specified and the current node have no common container node or the two nodes are different attributes of the same node.

Note: The return value could also be a combination of values. E.g. a return value of 20 means that the specified node is contained by the current node (16) AND the specified node follows the current node (4).

Technical Details

DOM Version Core Level 3 Node Object

Node Object Reference Node Object