XML DOM compareDocumentPosition() methode

Definitie en gebruik

compareDocumentPosition() Vergelijkt de positie van twee knopen in de DOM-hiërarchie (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 representing 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 not IE 9 and earlier versions. Therefore, in the above example, most browsers will output 4, while IE 9 and earlier versions will output 2.

Browser Ondersteuning

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Ondersteuning Ondersteuning Ondersteuning Ondersteuning Ondersteuning

Alle主流 browsers ondersteunen de compareDocumentPosition() methode.

Opmerking:Internet Explorer 9 en oudere versies ondersteunen deze methode niet.