XML DOM previousSibling 屬性

定義和用法
previousSibling 屬性返回元素之前緊接的節點(處於同一樹層級中)。
如果無此節點,則該屬性返回 null。
語法
nodeObject.previousSibling
提示和注釋
注釋:Firefox 以及大多數其他的流覽器,會把節點間生成的空的空格或者換行當作文本節點,而 Internet Explorer 會忽略節點間生成的空白文本節點。因此,在下面的實例中,我們會使用一個函數來檢查上一個同級節點的節點類型。
元素節點的節點類型是 1,因此如果上一個同級節點不是一個元素節點,它就會移至下一個節點,然後繼續檢查此節點是否為元素節點。整個過程會一直持續到上一個同級元素節點被找到為止。通過這個方法,我們就可以在所有的流覽器中得到正確的結果。
提示:如需瞭解更多有關流覽器差異的知識,請在我們的 XML DOM 教學中訪問我們的 DOM 流覽器 章節。
實例
下麵的代碼片段使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中,並從第一個 <author> 元素取得上一個同級節點:
實例
// 獲取元素節點的上一個同級節點
function get_previoussibling(n)
{
x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("author")[0];
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes[0].nodeValue);
y=get_previoussibling(x);
document.write("<br>Previous sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);
上面的代碼將輸出:
author = Giada De Laurentiis
Previous sibling: title = Everyday Italian
Previous sibling: title = Everyday Italian
嘗試一下
