nextSibling和previousSibling
在FireFox中包含众多空格作为文本节点,因此在我们使用nextSibling和previousSibling时就会出现问题。因为FireFox会把文本节点误当做元素节点的兄弟节点来处理。我们可以添加nodeType来判断。当上一节点或者是下一节点为文本节点时,就继续寻找,直到找到下一个元素节点。以下代码仅供参考,在fireFox中测试通过:
//下一个兄弟节点 function nextSibling(node) { var tempLast = node.parentNode.lastChild; if (node == tempLast) return null; var tempObj = node.nextSibling; while (tempObj.nodeType != 1 && tempObj.nextSibling != null) { tempObj = tempObj.nextSibling; } return (tempObj.nodeType==1)? tempObj:null; } //前一个兄弟节点 function prevSibling(node) { var tempFirst = node.parentNode.firstChild; if (node == tempFirst) return null; var tempObj = node.previousSibling; while (tempObj.nodeType != 1 && tempObj.previousSibling != null) { tempObj = tempObj.previousSibling; } return (tempObj.nodeType==1)? tempObj:null; }
测试代码
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" language="javascript" > window.onload = function () { var oUl = document.getElementsByTagName("UL"); var nodeLi = oUl[0].childNodes[3]; var nextListItem = nodeLi.nextSibling; var preListItem = nodeLi.previousSibling; alert(nextListItem.tagName + " " + preListItem.tagName); nextListItem = nextSibling(nodeLi); preListItem = prevSibling(nodeLi); alert(nextListItem.tagName + " " + preListItem.tagName); } //下一个兄弟节点 function nextSibling(node) { var tempLast = node.parentNode.lastChild; if (node == tempLast) return null; var tempObj = node.nextSibling; while (tempObj.nodeType != 1 && tempObj.nextSibling != null) { tempObj = tempObj.nextSibling; } return (tempObj.nodeType==1)? tempObj:null; } //前一个兄弟节点 function prevSibling(node) { var tempFirst = node.parentNode.firstChild; if (node == tempFirst) return null; var tempObj = node.previousSibling; while (tempObj.nodeType != 1 && tempObj.previousSibling != null) { tempObj = tempObj.previousSibling; } return (tempObj.nodeType==1)? tempObj:null; } </script> </head> <body> <form id="form1" runat="server"> <div> <ul> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>JQuery</li> <li>Dom</li> </ul> <ul> <li>ASP.NET</li> <li>JSP</li> <li>PHP</li> <li>VB.NET</li> </ul> </div> </form> </body> </html>
其中nodeType的值主要有以下几种:
- 元素节点的nodeType值为1
- 属性节点的nodeType值为2
- 文本节点的nodeType值为3