本文已参与「新人创作礼」活动,一起开启掘金创作之路
本文主要介绍如何利用DOM实现页面元素的添加、删除以及替换,同时介绍属性节点的创建。
1.添加元素
核心思路:先通过createElement()创建元素并通过createTextNode()添加其文本(或者直接用innerHTML或innerText),后利用父级并通过appendChild()或insertBefore()方法插入创建的元素。appendChild()会在父级最后的位置插入元素,insertBefore()则可以指定父级内的某个子元素,然后插入到该元素的前面。
2.删除元素
核心思路:
remove()方法:获取到元素之后直接调用即可,有些浏览器不支持。
removeChild()方法:需要通过父级才能删除相应的元素
3.替换元素:
核心思路:
通过父级指定想要替换的元素,利用replaceChild()即可替换,参数分别是创建的元素、要替换的元素。
4.复制元素:cloneNode()
克隆节点:参数默认为false,只复制标签,不复制内容.改为true,则既复制标签,也复制内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 1.创建节点(createElement()、createTextNode()、appendChild()/insertBefore())-->
<div id="div1">
<p id="p1">第一段文本</p>
<p>第二段文本</p>
</div>
<div id="div2">第二个div</div>
<p id='p2'>替换文本</p>
<section>section部分</section>
<script>
// (1).创建p标签节点.
var p = document.createElement('p');
// (2).创建其子文本节点“第三段文本”)
p.appendChild(document.createTextNode('第三段文本'));
// (3).给id名为“div1”的标签添加所创节点
document.getElementById('div1').appendChild(p);
document.getElementById('div1').insertBefore(p, document.getElementById('p1'));
// 同一个节点,只能插入一次。以靠后的操作为准。这里会执行insertBefore的操作
// appendChild会在父级元素的最后插入创建的元素
// insertBefore会在父级内某一指定的元素前插入创建的元素
//2.删除节点(remove().注意:remove() 方法在旧浏览器中不起作用,需要使用removeChild())
// remove()方法直接删
// document.getElementById("div2").remove();
// removeChild()则是通过父级删子级
document.body.removeChild(document.getElementById("div2"));
// 3.替换节点
var div2 = document.createElement('div');
div2.appendChild(document.createTextNode('第二个div'));
document.body.replaceChild(div2, document.getElementById('p2'));
// 4.复制节点
var anotherDiv = document.querySelector('section').cloneNode(true);
document.body.appendChild(anotherDiv);
</script>
</body>
</html>
5.属性节点的创建
利用createAtrribute创建属性,通过value设置属性值,最后通过setAttributeNode将该属性设置给相应元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
[index='1'] {
display: inline-block;
width: 200px;
height: 200px;
background-color: skyblue;
font-size: 30px;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<a href="http://www.baidu.com">百度</a>
<div><button>点击切换a标签模式</button></div>
<script>
var btn = document.querySelector('button');
var a = document.querySelector('a');
btn.onclick = function() {
var index = document.createAttribute('index');
index.value = '1';
a.setAttributeNode(index);
}
</script>
</body>
</html>
\