document.querySelector
和document.getElementById
選取元素。DOM 是瀏覽器把HTML 文件結構化成一個物件模型,讓 JavaScript 可以存取與操作。
你可以想像 DOM 是一棵樹 (Tree):
document
→ 代表整個網頁element
→ 標籤節點 (例如 <h1>
、<p>
、<button>
)attribute
→ 屬性 (例如 id="title"
)text
→ 文字內容// 依照 ID 取得元素
let title = document.getElementById("main-title");
// 使用 CSS 選擇器
let paragraph = document.querySelector(".content");
title.textContent = "Hello JavaScript!"; // 修改文字
paragraph.innerHTML = "<b>這段話被加粗了</b>"; // 修改 HTML
// 修改樣式
title.style.color = "red";
title.style.fontSize = "24px";
// 修改屬性
paragraph.setAttribute("title", "提示文字");
檔名:day14_dom.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day14 - DOM 基礎</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
color: blue;
}
button {
margin-top: 10px;
padding: 8px 12px;
cursor: pointer;
}
</style>
</head>
<body>
<h1 id="main-title">這是一個標題</h1>
<p class="content">這是一段文字,等等會被修改。</p>
<button id="changeBtn">點我改變文字顏色</button>
<script>
// 取得元素
const title = document.getElementById("main-title");
const paragraph = document.querySelector(".content");
const button = document.getElementById("changeBtn");
// 修改文字內容
paragraph.textContent = "這段文字已經被 JavaScript 改掉了!";
// 按鈕點擊事件:切換文字顏色
button.addEventListener("click", function() {
if (title.style.color === "blue") {
title.style.color = "red"; // 如果是藍色就改成紅色
} else {
title.style.color = "blue"; // 如果不是藍色就改回藍色
}
});
</script>
</body>
</html>