Método XML DOM compareDocumentPosition()
❮ Objeto de nodo
Ejemplo
El siguiente fragmento de código carga " books.xml " en xmlDoc y compara la ubicación de dos nodos (el primer y el tercer elemento <book>) en la jerarquía 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);
}
La salida del código anterior será:
4
La mayoría de los navegadores tratarán los espacios en blanco vacíos o las líneas nuevas como nodos de texto, IE 9 y versiones anteriores no lo harán. Entonces, en el ejemplo anterior, la mayoría de los navegadores generarán 4, mientras que IE 9 y versiones anteriores generarán 2.
Definición y uso
El método compareDocumentPosition() compara la ubicación de dos nodos en la jerarquía DOM (documento).
Compatibilidad con navegador
El método compareDocumentPosition() es compatible con todos los navegadores principales.
Nota: Internet Explorer 9 y versiones anteriores no admiten este método.
Sintaxis
nodeObject.compareDocumentPosition(node)
Parámetros
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare with the current node |
Valor de retorno
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). |
Detalles técnicos
Versión DOM | Objeto de nodo de nivel 3 básico |
---|
❮ Objeto de nodo