XML DOM previousSibling property
Definition and Usage
previousSibling
The property returns the node immediately preceding the node (the subsequent node at the same tree level).
If such a node does not exist, this property returns null.
Syntax
nodeObject.previousSibling
Note:Firefox and most other browsers treat whitespace or line breaks as text nodes, while Internet Explorer does not. In the following example, we use a function to check the node type of the previous sibling node.
Element node's nodeType is 1, so if the previous sibling node is not an element node, move to the next node and check if the node is an element node. This will continue until the previous sibling node (must be an element node) is found. This ensures that the result is correct in all browsers.
Wskazówka:Aby uzyskać więcej informacji na temat różnic między przeglądarkami, odwiedź rozdział DOM przeglądarki w tutorialu XML DOM.
Przykład
Przykład 1
Poniższy kod załaduje "books.xml" do xmlDoc i pobra z pierwszego elementu <author> poprzedniego brata:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Sprawdź, czy poprzedni brat jest węzłem elementu 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 + "<br>Poprzedni brat: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }
Przykład 2
Pobierz następny brat węzła:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Sprawdź, czy następny brat jest węzłem elementu 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>Następny brat: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }