<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="block">
這是 div 區塊
<p class="para">這是段落</p>
</div>
<br>
<button type="button" id="btn1">取得內容</button>
<button type="button" id="btn2">更新內容</button>
<button type="button" id="btn3">刪除元素節點</button>
<button type="button" id="btn4">建立元素節點</button>
<script></script>
</body>
</html>
<style>
div.block{
border: 1px solid black;
color: red;
}
p.para{
border: 1px solid blue;
color: blue;
}
</style>
// 取得內容
var btn1 = document.getElementById("btn1");
btn1.addEventListener("click", function(){ // click 事件綁定
let block = document.getElementsByClassName("block")[0];
console.log(block.innerHTML);
});
// 更新內容
var btn2 = document.getElementById("btn2");
btn2.addEventListener("click", function(){
let block = document.getElementsByClassName("block")[0];
block.innerHTML = "<h1>變成新的標題。</h1>";
});
// 刪除元素節點
var btn3 = document.getElementById("btn3");
btn3.addEventListener("click", function(){ // click 事件綁定
let h1_el = document.getElementsByTagName("h1")[0];
if(h1_el){
h1_el.remove();
}
});
// 建立元素節點
var btn4 = document.getElementById("btn4");
btn4.addEventListener("click", function(){ // click 事件綁定
let block = document.getElementsByClassName("block")[0];
let p_str = '<p>新貼入的文字</p>';
// beforebegin, afterbegin, beforeend, afterend
block.insertAdjacentHTML("beforeend", p_str);
});