javascript 中的nextSibling和previousSibling使用注意事项

JavaScript中的nextSiblingpreviousSibling和作用类似于jquery的next()和prev(),都是获取下一个/上一个同胞元素,如果下一个同级节点不存在,则此属性返回值是null。但是具体的使用中还是有差异的,如果注意。就会引起错误

html结构中的各种空格,换行符都可能会把文本节点当做同胞元素处理。这就会导致错误。

例如下面代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    window.onload = function() {
        var nextType = document.getElementById('one').nextSibling;
        alert(nextType.nodeType);
    }
    </script>
</head>
<body>
    <div id="div">
        <p id = "one">我是p</p>
        <span id="two">我是span</span>
    </div>
</body>
</html>

在上面这段代码中,我获取了id为"one"的元素并用nextSibling获取了他的下一个同胞元素。赋值给了变量nextType

   var nextType = document.getElementById('one').nextSibling;

  并使用

  alert(nextType.nodeType);

弹出他的节点类型,如果按常理,元素p下一个相邻的同胞元素为是span,弹出的数字应该为“1”,但我再火狐,谷歌,IE浏览器(网上说只有火狐才会把换行,空格当做文本节点处理,但是我测试谷歌,IE浏览器效果都是一样的,这有点不解)打开后,弹出的数字是3,

也就是文本节点。这是因为换行符被当做文本节点来处理,成为了p元素的下一个同胞元素。

如果我要获取我是span的文本值,需要这样写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    window.onload = function() {
        var nextType = document.getElementById('one').nextSibling;
        var span = nextType.nextSibling;
     alert(span.lastChild.nodeValue);
   }
    </script>
</head>
<body>
    <div id="div">
        <p id = "one">我是p</p>
        <span id="two">我是span</span>
    </div>
</body>
</html>

p和span标签中间隔着文本节点,需要连续使用2次nextSibling才能选中span标签取得文本值

firstChild,lastChild,nextSibling,previousSibling都会将空格或者换行当做节点处理,但是有代替属性

所以为了准确地找到相应的元素,会用

firstElementChild,

lastElementChild,

nextElementSibling,

previousElementSibling

兼容的写法,这是JavaScript自带的属性。

但坏消息是IE6,7,8不兼容这些属性。IE9以上和火狐谷歌支持。

于是我写了一个接口口,测试能在包括ie6在内运行的函数(自己写的,不知有没有其他什么细节错误没注意,反正能运行并且过滤文本节点获取正确的下一个元素节点)

    function getNextElement(element){
            var e = element.nextSibling;
            if(e == null){//测试同胞节点是否存在,否则返回空
                return null;
            }
            if(e.nodeType==3){//如果同胞元素为文本节点
                var two = getNextElement(e);
                if(two.nodeType == 1)
                    return two;
            }else{
                if(e.nodeType == 1){//确认节点为元素节点才返回
                    return e;
                }else{
                    return false;
                }
            }
        }
原文地址:https://www.cnblogs.com/lijinwen/p/5690223.html