-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-node.html
More file actions
76 lines (60 loc) · 2.62 KB
/
create-node.html
File metadata and controls
76 lines (60 loc) · 2.62 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ノードの追加・挿入・削除</title>
<style>
.container {
outline: 1px solid black;
}
</style>
</head>
<body>
<h1>ノードの追加・挿入・削除のサンプル</h1>
<hr />
<div id="container1" class="container"></div>
<hr />
<div id="container2" class="container"></div>
<script>
const container1 = document.getElementById("container1");
const container2 = document.getElementById("container2");
// --- ▼ ノードの作成 --- //
// 要素ノードの作成
const p1 = document.createElement("p");
const p2 = document.createElement("p");
p1.textContent = "これはp要素1です";
p2.textContent = "これはp要素2です";
// テキストノードの作成
const tx1 = document.createTextNode("これはテキストノード1です");
const tx2 = document.createTextNode("これはテキストノード2です");
const tx3 = document.createTextNode("これはテキストノード3です");
// コメントノードの作成
const cm = document.createComment("これはコメントノードです");
// --- ▼ ノードの挿入 --- //
// 子ノードとして挿入( Node.appendChild()版 )
container1.appendChild(p2);
// 子ノードとして挿入( Element.appendChild()版 )
container2.appendChild(tx2,cm,"文字列もそのまま追加できます");
// 兄弟ノードとして親要素の子ノードリストへ挿入
tx2.before(tx1);//tx2の前にtx1を追加する
tx2.after(tx3);//tx2の後にtx3を追加する
// 位置を指定してノードを追加
container1.insertBefore(p1,p2);
// ◀ p要素2の前に挿入
// --- ▼ ノードの削除(実行する場合はコメント化を解除してください) --- //
// 要素ノードを削除
p1.remove();//p1自身を削除
// 子ノードを指定して削除
container2.removeChild(tx1);//container2の子要素であるtx1を指定して削除
// 子ノードをすべて削除( Element.remove()版 )
while(container1.firstChild){
container1.firstChild.remove();
}
// 子ノードをすべて削除( Node.removeChild()版 )
while(container2.firstChild){
container2.removeChild(container2.firstChild);
}
</script>
</body>
</html>