函数判断上下兄弟结点

因为浏览器解析之间差异,在选择兄弟结点时,多数浏览器将元素间的换行符作为了文本结点.这样的情况同样存在于查看元素的子结点时.
使用childNodes查看元素第一层子结点列表.

Tips:You can change the code before run.

IE的输出中只有4个元素,FF同样将元素间的换行符作为了文本结点.

所以使用nextSibling,previousSibling并不能准确返回一个元素.
使用closestSibling方法避免这个问题,其中direction 为1时表示下一个兄弟结点,-1表示上一个兄弟结点:

function closestSibling(node,direction){
var tempObj;
if(direction==-1 && node.previousSibling!=null){
tempObj=node.previousSibling;
while(tempObj.nodeType!=1 && tempObj.previousSibling!=null){
tempObj=tempObj.previousSibling;
}
}else if(direction==1 && node.nextSibling!=null){
tempObj=node.nextSibling;
while(tempObj.nodeType!=1 && tempObj.nextSibling!=null){
tempObj=tempObj.nextSibling;
}
}
return tempObj.nodeType==1?tempObj:false;
},

随机日志

2 Responses

  1. JaneRadriges
    14 06,2009 / 11:19

    Hi, interest post. I’ll write you later about few questions!

    ReplyReply
  2. Fay
    31 08,2009 / 07:42

    Nice write up…usually I never reply to these thing but this time I will,Thanks for the great info.

    ReplyReply

Leave a Reply