元素遍历

<body>
    <div>klkx1</div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
    <div>klkx2</div>
    <script>
        var oUl = document.getElementsByTagName('ul')[0];
        var s1 = oUl.childElementCount;//返回父级元素的子元素个数,不包括文本元素和注释
        console.log( s1 );
        var s2 = oUl.firstElementChild;//指向第一个子元素;firstChild的元素版
        console.log( s2 );
        /*
        var s3 = oUl.firstChild;//firstChild包括文本元素
        console.log( s3 );
        */
        var s3 = oUl.lastElementChild;
        console.log( s3 );//指向最后一个子元素;lastChild的元素版
        var s4 = oUl.previousElementSibling;//指向前一个同辈元素
        console.log( s4 );
        var s5 = oUl.nextElementSibling;//指向前一个同辈元素
        //s5.style.background = 'red';
        console.log( s5 );
    </script>
 </body>

这些属性,不必担心空白文本节点

原文地址:https://www.cnblogs.com/jokes/p/9529249.html