DOM节点的创建、插入、删除

it2022-05-07  21

值得注意的是:节点的创建、插入以及删除都是操作父级容器。(1)创建var newDiv = documnet.createElement('div'); ——创建的元素只能操作一次

(2)插入/追加appendChild() 从尾部追加元素 red.appendChild('newDiv);insertBefore() 在某个元素之前插入 red.insertBefore(newDiv,firstChild);

(3)删除节点red.removeChild(lastChild);

========================相关示例代码如下================================

<!DOCTYPE html>

<html lang="en">

<head>

        <meta charset="UTF-8">

        <title>practice</title>

        <style>

                 #red{

                         width: 400px;

                         height: 400px;

                         border:1px solid #ccc;

                 }

                 .active1{

                         width: 200px;

                         height: 200px;

                         background: pink;

                         border-radius: 50%;

                         margin-top: 20px;

                         margin-left: 10px;

                 }

                 .active2{

                         width: 100px;

                         height: 100px;

                         background: green;

                         border-radius: 50%;

                         margin-top: 20px;

                         margin-left: 10px;

                 }

        </style>

</head>

<body>

        <div id="red"></div>

        <button id="delete">删除节点</button>

</body>

<script>

        var red = document.getElementById('red');

        //document.createElement()创建元素;注意创建的元素只能操作一次

        var newDiv1 = document.createElement('div');

        newDiv1.className = 'active1';

        //追加元素

        red.appendChild(newDiv1);

        //重新创建newDiv2,因为newDiv1只能操作一次

        var newDiv2 = document.createElement('div');

        newDiv2.className = 'active2';

        red.appendChild(newDiv2);

 

        //获取第一个子元素节点firstElementChild

        var firstChild = red.firstElementChild;

        console.log(firstChild);

        //获取最后一个子元素节点lastElementChild

        var lastChild = red.lastElementChild;

        console.log(lastChild);

 

        //在第一个子元素节点之前插入元素

        var newDiv3 = document.createElement('div');

        newDiv3.innerHTML = 'today is nice!';

        red.insertBefore(newDiv3,firstChild);

 

        //在第二子元素节点之前插入元素

        var newDiv4 = document.createElement('div');

        newDiv4.innerHTML = 'middle position!';

        red.insertBefore(newDiv4,lastChild);

 

        //删除节点

        var remove = document.getElementById('delete');

        remove.onclick = function(){

                 red.removeChild(newDiv4);

        }

</script>

</html>

转载于:https://www.cnblogs.com/sherryStudy/p/dom_node.html


最新回复(0)