Home  >  Q&A  >  body text

javascript - insertbefore issue with replacing parent element

Code before modification

<!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>

Modified code

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

            console.log( h1 );

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

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

After modification, elements cannot be added. What is the problem. The previous addition had body as the parent element and was used directly without passing it. I have nested a p and obtained the elements in advance. But still cannot insert new elements

欧阳克欧阳克2658 days ago756

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-06-14 10:54:13

    The boxes you created are not in the document. Where should you insert them?

    reply
    0
  • 某草草

    某草草2017-06-14 10:54:13

    1. createElement can only create labels. Box is not considered a label, right? Replace var box = document.createElement('box'); with var box = document.createElement('p');
    2. This tag only exists in the Body, you cannot get it directly through document.box,
    You have done it before What is written is var box=document.createElement('box');
    document.box Isn't that equivalent to document.document.createElement('box')?
    First add a class name to get it

    reply
    0
  • Cancelreply