Propiedad nextSibling del XML DOM
Definición y uso
nextSibling
Esta propiedad devuelve el siguiente nodo同级 del elemento seleccionado (el siguiente nodo en el mismo nivel del árbol).
Si no existe tal nodo, esta propiedad devuelve null.
Sintaxis
elementNode.nextSibling
Nota:Firefox y la mayoría de los otros navegadores considerarán 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 tanto, 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同级 (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, visite la sección DOM Navegadores del tutorial XML DOM.
Ejemplo
Ejemplo 1
El siguiente código cargará "books.xml" en xmlDoc y obtendrá 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(); // Verificar 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
Utilice el método previousSibling para 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(); // Verificar 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; {}