打赏

js 原生方法获取所有兄弟节点

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>js 原生方法获取所有兄弟节点</title>
    </head>

    <body>
        <ul>
            <li id="first">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <script type="text/javascript">
            //方法一:
            //            function sibling(elem) {
            //                var r = [];
            //                var n = elem.parentNode.firstChild;
            //                for(; n; n = n.nextSibling) {
            //                    if(n.nodeType === 1 && n !== elem) {
            //                        r.push(n);
            //                    }
            //                }
            //                return r;
            //            }
            //方法二
            function sibling(elm) {
                var a = [];
                var p = elm.parentNode.children;
                for(var i = 0, pl = p.length; i < pl; i++) {
                    if(p[i] !== elm) a.push(p[i]);
                }
                return a;
            }

            var siblings = sibling(document.getElementById('first'));
            console.log(siblings);
        </script>
    </body>

</html>

 

posted @ 2018-05-22 10:42  孟繁贵  阅读(8862)  评论(0编辑  收藏  举报
TOP