Atributo nextSibling del XML DOM
Definición y uso
nextSibling
La propiedad devuelve el nodo siguiente a un nodo determinado (el siguiente nodo en el mismo nivel de árbol).
Si no existe tal nodo, esta propiedad devuelve null.
Sintaxis
nodeObject.nextSibling
Nota:Firefox y la mayoría de los otros navegadores consideran los espacios en blanco o las salidas de línea como nodos de texto, mientras que Internet Explorer no. Por lo tanto, en el siguiente ejemplo, utilizamos una función para verificar el tipo de nodo del siguiente nodo hermano.
El nodeType del nodo de elemento es 1, por lo que si el siguiente nodo hermano no es un nodo de elemento, se mueve al siguiente nodo y verifica si ese nodo es un nodo de elemento. Esto continuará hasta que se encuentre el siguiente nodo hermano igual (debe ser un nodo de elemento). De esta manera, el resultado es correcto en todos los navegadores.
Consejo:Para obtener más información sobre las diferencias entre navegadores, consulte la sección DOM Navegador del tutorial XML DOM.
Ejemplo
Ejemplo 1
El siguiente código carga "books.xml" en xmlDoc y obtiene el siguiente nodo hermano del primer elemento <title>:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Comprobar si el nodo hermano siguiente es un nodo de elemento function get_nextsibling(n) { var x = n.nextSibling; while (x.nodeType != 1) { x = x.nextSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("title")[0]; var y = get_nextsibling(x); document.getElementById("demo").innerHTML = x.nodeName + " = " + x.childNodes[0].nodeValue + "<br>Hermano siguiente: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }
Ejemplo 2
Obtener el nodo hermano anterior:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Comprobar si el nodo hermano anterior es un nodo de elemento function get_previoussibling(n) { var x = n.previousSibling; while (x.nodeType != 1) { x = x.previousSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("author")[0]; var y = get_previoussibling(x); document.getElementById("demo").innerHTML = x.nodeName + " = " + x.childNodes[0].nodeValue + "Antecesor hermano: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }