Metodo XML DOM compareDocumentPosition()
❮ Oggetto nodo
Esempio
Il seguente frammento di codice carica " books.xml " in xmlDoc e confronta il posizionamento di due nodi (il primo e il terzo elemento <book>) nella gerarchia DOM:
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);
}
L'output del codice sopra sarà:
4
La maggior parte dei browser tratterà gli spazi vuoti o le nuove righe come nodi di testo, IE 9 e precedenti no. Quindi, nell'esempio sopra, la maggior parte dei browser produrrà 4, mentre IE 9 e precedenti produrranno 2.
Definizione e utilizzo
Il metodo compareDocumentPosition() confronta il posizionamento di due nodi nella gerarchia DOM (documento).
Supporto browser
Il metodo compareDocumentPosition() è supportato in tutti i principali browser.
Nota: Internet Explorer 9 e versioni precedenti non supportano questo metodo.
Sintassi
nodeObject.compareDocumentPosition(node)
Parametri
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare with the current node |
Valore di ritorno
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). |
Dettagli tecnici
Versione DOM | Oggetto nodo di livello 3 di base |
---|
❮ Oggetto nodo