js中改变文档的层次结构(创建元素节点,添加结点,插入子节点,取代子节点,删除子节点)...

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

<style type="text/css">
.box1,
.box2{
width: 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" οnclick="testCreate()" value="create">
<input type="button" οnclick="testInertBefore()" value="testInertBefore">
<input type="button" οnclick="testReplaceChild()" value="testReplaceChild">
<input type="button" οnclick="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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值