Dom3 首尾节点&兄弟节点

2017-03-15  本文已影响0人  maomizone

1 firstChild / lastChild

2 nextSibling / previousSibling

适用于IE6-8 高版本浏览器存在兼容问题 能找到文字节点,这是我们不希望看到的

3 firstElementChild/ lastElementChild

4 nextElementSibling / previousElementSibling

适用于高级浏览器

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        window.onload = function(){
            var ul = document.getElementById("ul");
            //IE6-8没有问题
            alert(ul.firstChild.nodeType);  // 3 说明一段空格被视为首节点 
            //高级浏览器
            alert(ul.firstElementChild.nodeType);  // 1 chrome测试
            
            //处理兼容问题
            if(ul.firstElementChild){ //如果firstElementChild存在 为真
                alert(ul.firstElementChild.nodeType);
            }else{
                alert(ul.firstChild.nodeType);
            }
            
        }
    </script>
</head>
<body>
<ul id="ul">
    <li></li>
    <li></li>
    <li></li>
   
</ul>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读