XML DOM previousSibling属性
定义和用法
previousSibling
属性返回所选元素的前一个同级节点(同一树级别中的前一个节点)。
如果不存在这样的节点,则该属性返回null。
语法
elementNode.previousSibling
注意:Firefox和大多数其他浏览器会将空白或换行视为文本节点,而Internet Explorer不会。因此,在下面的例子中,我们用一个函数来检查前一个同级节点的节点类型。
Element节点的nodeType为1,因此如果前一个同级节点不是元素节点,则移动到前一个节点,并检查该节点是否是元素节点。这将继续下去,直到找到前一个同级节点(必须是元素节点)。这样,结果在所有浏览器中都是正确的。
Hint:For more information on differences between browsers, please visit the DOM Browser section in the XML DOM tutorial.
Example
Example 1
The following code loads "books.xml" into xmlDoc and gets the previous sibling node of the first <author> element:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Check if the previous sibling node is an element node 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>Previous sibling: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }
Example 2
Using nextSibling, get the next sibling node of the element:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Check if the next sibling node is an element node 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>Next sibling: " + y.nodeName + " = " + y.childNodes[0].nodeValue; }