zoukankan      html  css  js  c++  java
  • js中改变文档的层次结构(创建元素节点,添加结点,插入子节点,取代子节点,删除子节点)

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>

    <style type="text/css">
    .box1,
    .box2{
    300px;
    height: 250px;
    margin-top: 10px;
    margin-bottom: 30px;
    border: 1px solid green;
    }

    .box1 > div,
    .box2 > div{
    border: 1px solid red;
    margin: 5px;
    padding: 10px 5px;
    }
    </style>

    <script type="text/javascript">
    //测试创建元素
    function testCreate(){
    var div = document.createElement("div");
    div.innerHTML = "this is a new div";
    div.style.color = "green";
    var target = document.querySelector('.box1');
    var target2 = document.querySelector('.box2');
    target.appendChild(div);
    //cloneNode 克隆元素 传值为true的时候 为深层次克隆 false为浅层次克隆
    target2.appendChild(div.cloneNode(true));
    }

    function testInertBefore(){
    var box11 = document.querySelector(".box1 > .box11");
    var box22 = document.querySelector(".box2 > .box22");

    var parent = document.querySelector(".box2");

    parent.insertBefore(box11.cloneNode(true),box22);
    }

    function testReplaceChild(){
    var box11 = document.querySelector(".box1 > .box11");
    var box22 = document.querySelector(".box2 > .box22");
    var parent = document.querySelector(".box2");

    parent.replaceChild(box11,box22);
    }
    function testRemoveChild(){
    var box22 = document.querySelector(".box2 > .box22");
    var parent = document.querySelector(".box2");

    parent.removeChild(box22);
    }

    </script>
    </head>
    <body>
    <input type="button" onclick="testCreate()" value="create">
    <input type="button" onclick="testInertBefore()" value="testInertBefore">
    <input type="button" onclick="testReplaceChild()" value="testReplaceChild">
    <input type="button" onclick="testRemoveChild()" value="testRemoveChild">
    <hr>
    <div class="box1">
    <div class="box11">this is a div test 11</div>
    <div class="box12">this is a div test 12</div>
    <div class="box13">this is a div test 13</div>
    <div class="box14">this is a div test 14</div>
    </div>
    <div class="box2">
    <div class="box21">this is a div test 21</div>
    <div class="box22">this is a div test 22</div>
    <div class="box23">this is a div test 23</div>
    <div class="box24">this is a div test 24</div>
    </div>
    </body>
    </html>
  • 相关阅读:
    关于分区索引对齐
    SQLSERVER 分区表实战
    鱼骨图实践
    Python之路-python(面向对象一)
    Python之路-python(常用模块学习)
    Python之路-python(装饰器、生成器、迭代器、Json & pickle 数据序列化、软件目录结构规范)
    Python之路-python(set集合、文本操作、字符编码 )
    Python之路-python数据类型(列表、字典、字符串、元祖)操作
    Python之路-python环境安装和简单的语法使用
    javascript中with语句应用
  • 原文地址:https://www.cnblogs.com/hwgok/p/5739824.html
Copyright © 2011-2022 走看看