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>
原文地址:https://www.cnblogs.com/hwgok/p/5739824.html