如何添加兄弟节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/csdnlinyongsheng/article/details/82983446

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button id="btn">按钮</button>
    <div class="box1">盒子1</div>

    <script>
        var btn = document.getElementById("btn");
        var box1 = document.querySelector(".box1");
        var box2Div = document.createElement("div");
        box2Div.className = "box2";

        btn.onclick = function(){
            insertAfter(box2Div, box1);
        }
        function insertAfter(newElement, targetElement){
            var parent = targetElement.parentNode; 
            console.log(parent);   
            if (parent.lastChild == targetElement) {  
                  // 如果最后的节点是目标元素,则直接添加。因为默认是最后        
                parent.appendChild(newElement);    
            } 
            else 
            {        
                parent.insertBefore(newElement, targetElement.nextSibling);      
                  //如果不是,则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面    
            }
        }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/csdnlinyongsheng/article/details/82983446