-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathremoveOrReplace.html
43 lines (32 loc) · 1.11 KB
/
removeOrReplace.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>removeOrReplace</title>
</head>
<body>
<div id="a">年轻人</div>
<div id="b">老年人</div>
<div id="c">拉姆</div>
<div id="d">蕾姆</div>
<script>
// 通过 parentNode 获取父元素,然后删除对应的子元素,Node 上
let diva = document.getElementById('a')
let divbfc = document.getElementById('b').firstChild
diva.parentNode.removeChild(diva)
divbfc.parentNode.removeChild(divbfc)
console.log(document.body.innerHTML)
// 通过 parentNode 获取父元素,然后替换对应的子元素,Node 上
let divc = document.getElementById('c')
let span = document.createElement('span')
span.textContent = '486'
divc.parentNode.replaceChild(span, divc)
let divd = document.getElementById('d')
let textNode = document.createTextNode('艾米莉亚')
divd.parentNode.replaceChild(textNode, divd)
console.log(document.body.innerHTML)
// DOM4 为 Element 引入了 replace、remove
// 替换或删除以后会返回对应节点的引用,此时要注意内存泄漏的问题
</script>
</body>
</html>