Home  >  Q&A  >  body text

javascript - When deleting DOM using removechild, you need to get the parent element first, but when insertbefore, you don't need to go to the parent element. and can be used directly

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    
    <button id='btn'>创建元素</button>
    
    <script type="text/javascript">
        
        var btn = document.getElementById('btn');
        
        //注册点击事件
        btn.onclick = function(){
            //创建一个元素
            var h1 = document.createElement('h1');
            h1.innerHTML = "这是新增h1标签";

            console.log( h1 );

            //使用appendChild的方式
            //document.body.appendChild( h1 );
            
            //使用insertBefore的方式
            //是在父元素中,先找一个节点,然后插入到它之前
            document.body.insertBefore(h1,btn); //新插入的节点是h1,作为第一个参数
        }

    </script>
</body>
</html>

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    
    <p id="box">
        <h2>删除操作</h2>
        <p>段落1</p>
    </p>
    
    <button id='btn'>删除</button>
    
    <script type="text/javascript">
        
        //找父节点p
        //var box = document.getElementById('box');
        //找子节点h2
        var h2 = document.getElementsByTagName('h2')[0];
        
        var btn = document.getElementById('btn');
        btn.onclick = function() {
            //box.removeChild( h2 );
            h2.parentNode.removeChild( h2 );
        }
    </script>

</body>
</html>
学习ing学习ing2658 days ago809

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-14 10:55:43

    DOM API is designed this way.

    body is the parent element of h1.

    Although h1 is an Element, this method inherits Node.

    Node.insertBefore()

    Grammar

    var insertedElement = parentElement.insertBefore(newElement, referenceElement);
            |                   |                       |               |
        被插入的节点             |                  被插入的节点          |
                           新插入节点的父节点                             |
                                                              插入newElement之前的那个节点               
    

    Parameters and return values

    • insertedElement is the inserted node, i.e. newElement

    • parentElement is the parent node of the newly inserted node

    • newElement is the inserted node

    • referenceElement The node before inserting newElement


    Look at Node.removeChild again

    Grammar

    let oldChild = node.removeChild(child);
    
    // OR
    
    element.removeChild(child);
    

    Parameters

    • child is the child node to be removed.

    • node is the parent node of child.

    • oldChild Saves a reference to the deleted child node. oldChild === child.

    reply
    0
  • 迷茫

    迷茫2017-06-14 10:55:43

    body is also an element.

    reply
    0
  • Cancelreply