javascript - insertbefore issue with replacing parent element
欧阳克
欧阳克 2017-06-14 10:52:13
0
2
910

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

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(2)
漂亮男人

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

某草草

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template