封裝js獲取當前元素的弟弟元素節點

weixin_34232744發表於2019-01-15

第一種方法

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
    <ul id="list">
        <li id="item1">item1</li>
        <li id="item2">item2</li>
        <li id="item3">item3</li>
        <li id="item4">item4</li>
        <li id="item5">item5</li>
        <li id="item6">item6</li>
        <li id="item7">item7</li>
        <li id="item8">item8</li>
        <li id="item9">item9</li>
        <li id="item10">item10</li>
    </ul>
    <script>
        var item10=document.getElementById('list');
        var item1=document.getElementById('item1');
        var item2=document.getElementById('item2');
        var item3=document.getElementById('item3');
        var item4=document.getElementById('item4');
        var item5=document.getElementById('item5');
        var item6=document.getElementById('item6');
        var item7=document.getElementById('item7');
        var item8=document.getElementById('item8');
        var item9=document.getElementById('item9');
        var item10=document.getElementById('item10');
        function getLittleBrother(curEle){
            var nB=curEle.nextSibling;
            while(nB){
                if(nB.nodeType===1){
                   return nB
                }else{
                    nB=nB.nextSibling;
                }
            }   
        }
        console.log(getLittleBrother(item3));
    </script>
</body>
</html>
複製程式碼

第二種方法

  // 獲取當前元素的弟弟元素節點
        console.log(getNext(lis));
        function getNext(curEle) {
            var temp = curEle.nextSibling;
            while (temp){
                if (temp.nodeType === 1){
                    return temp;
                }
                temp = temp.nextSibling;
            }
            return null;
        }
複製程式碼

相關文章