DOM操作

一 概念 


```js
// 创建一个div标签
var div = document.createElement("div");
// 添加到body末尾,返回自身
div = body.appendChild(div);
// 插入到body中box标签前,返回自身
div = body.insertBefore(div, box);
// 替换掉body中box标签,返回box
box = body.replaceChild(div, box);
// 在body中移除div,返回自身
div = body.removeChild(div);
```

## 三、JS操作DOM一般步骤

#### 1、创建标签

#### 2、设置标签样式文本

#### 3、添加到页面指定位置

二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>DOM操作</title>
<style type="text/css">
.box {
width: 200px;
height: 200px;
background-color: red;
}
.p {
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div class="box">box box box bi box</div>
<button class="b1">添加到box中</button>
<button class="b2">添加到body中</button>
<button class="b3">插到body下box之前</button>
<button class="b4">将body下box替换为p</button>
<button class="b5">删除box</button>
</body>
<script type="text/javascript">
var body = document.querySelector('body');
var box = document.querySelector('.box');
var b1 = document.querySelector('.b1');
var b2 = document.querySelector('.b2');
var b3 = document.querySelector('.b3');
var b4 = document.querySelector('.b4');
var b5 = document.querySelector('.b5');

// 创建标签p
var p = document.createElement('p');
console.log(p);

// 设置标签样式
p.className = 'p';

// 添加到指定区域
b1.onclick = function () {
var res = box.appendChild(p);
console.log(res); // 自身
}
b2.onclick = function () {
body.appendChild(p);
}

// 总结:
// 1.创建标签只能由document来调用执行
// 2.一次创建只产生一个标签对象,该标签对象只能存在最后一次操作的位置


// 插入到指定区域
b3.onclick = function () {
// 将p插到box之前(前者插入到后者之前)
var res = body.insertBefore(p, box);
console.log(res); // 自身
// box和p都是body的一级子标签后,顺序有需求决定
// body.insertBefore(box, p);
}

b4.onclick = function () {
// 将p替换掉box(前者替换后者)
var res = body.replaceChild(p, box);
console.log(res); // box
}

b5.onclick = function () {
// 由父级删除指定子级
// var res = body.removeChild(box);
// 获取父级来删除自身
var res = box.parentElement.removeChild(box);

console.log(res); // box
setTimeout(function () {
// 删除后,标签对象依然可以被js保存,继而可以重新添加到页面
body.appendChild(res);
}, 1000)
}

</script>
</html>

posted @ 2018-10-23 15:30  不沉之月  阅读(61)  评论(0编辑  收藏  举报