THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

XML DOM compareDocumentPosition() Method


Element Object Reference Element 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.

To read more about the differences between browsers, visit our DOM Browsers chapter in our XML DOM Tutorial.


Definition and Usage

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

Syntax

elementNode.compareDocumentPostition(node)

Parameter Description
node Required. Specifies the node to compare with the current node

Element Object Reference Element Object