XML-DOM -compareDocumentPosition()- Methode
❮ Knotenobjekt
Beispiel
Das folgende Codefragment lädt „ books.xml “ in xmlDoc und vergleicht die Platzierung von zwei Knoten (dem ersten und dem dritten <book>-Element) in der DOM-Hierarchie:
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);
}
Die Ausgabe des obigen Codes lautet:
4
Die meisten Browser behandeln leere Leerzeichen oder neue Zeilen als Textknoten, IE 9 und früher nicht. Im obigen Beispiel geben die meisten Browser also 4 aus, während IE 9 und früher 2 ausgeben.
Definition und Verwendung
Die Methode CompareDocumentPosition() vergleicht die Platzierung zweier Knoten in der DOM-Hierarchie (Dokument).
Browser-Unterstützung
Die Methode CompareDocumentPosition() wird von allen gängigen Browsern unterstützt.
Hinweis: Internet Explorer 9 und früher unterstützen diese Methode nicht.
Syntax
nodeObject.compareDocumentPosition(node)
Parameter
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare with the current node |
Rückgabewert
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). |
Technische Details
DOM-Version | Knotenobjekt der Kernebene 3 |
---|
❮ Knotenobjekt