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

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!