JavaScript/文件物件模型 (DOM) 簡介
外觀

HTML 頁面在內部由一個樹實現,該樹包含 HTML 元素(以及 CSS 樣式)作為其節點。這棵樹稱為文件物件模型,或 DOM。JavaScript 可以完全訪問 DOM。它可以遍歷樹,修改樹和節點,從簡單地新增新節點到重新排列頁面上的多個區域。
關於術語的提示:由於它與 XML 非常接近,HTML 使用術語元素;由於它的樹狀結構,DOM 使用術語節點。
當載入到瀏覽器中時,HTML 文件被分解成一個樹,由節點組成。例如,看看下面的 HTML 片段
<div id="exampleDiv">This is an<br>example HTML snippet.</div>
透過 DOM,JavaScript 將此片段視為四個節點。
div,從它的開始標籤到它的結束標籤,是一個節點。這個div恰好在它的開始標籤內被分配了一個屬性。此屬性名為 "id",其值為 "exampleDiv"。
- 此示例中的另外三個節點位於
div內。它們被稱為div的子節點,因為div包含它們。相反,div是它們的父節點。
div的第一個子節點是文字節點,其值為 "This is an"。文字節點僅包含文字;它們永遠不會包含標籤,這就是為什麼樹在這裡停止的原因。br標籤是另一個節點。- 其餘文字是另一個文字節點。
由於文字節點和 br 標籤共享同一個父節點,因此它們被稱為兄弟節點。
您可以透過各種方法訪問 DOM 樹的節點。其中之一是 getElementById。
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
"use strict";
const p = document.getElementById("p2");
alert(p.innerHTML);
}
</script>
</head>
<body id="body">
<p id="p1" style="background: aqua">one</p>
<p id="p2" style="background: green">two</p>
<p id="p3" style="background: red">three</p>
<button onclick="go()">Show the second paragraph</button>
</body>
</html>
當點選按鈕時,函式 go 被呼叫。它訪問 id 為 'p2' 的元素並顯示其內容。
如果您想訪問節點的內容,可以使用不同類別的不同屬性:Node.textContent,HTMLElement.innerText,或 Element.innerHTML。但它們並不相等;請考慮差異。為了使我們的示例清晰易懂,我們儘可能使用 Element.innerHTML,因為它非常接近 HTML 原始碼。
const exampleContent = document.getElementById("example").innerHTML;
訪問節點後,您可以透過為其內容分配一個新值來更改其內容。
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
"use strict";
const p = document.getElementById("p2");
p.innerHTML = "Another text";
}
</script>
</head>
<body id="body">
<p id="p1" style="background: aqua">one</p>
<p id="p2" style="background: green">two</p>
<p id="p3" style="background: red">three</p>
<button onclick="go()">Change the second paragraph</button>
</body>
</html>
當點選按鈕時,函式 go 被呼叫。它再次訪問 id 為 'p2' 的元素並更改其內容。
JavaScript 可以操作 DOM 樹的結構。
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
"use strict";
// read 'body' node
const b = document.getElementById("body");
// read second 'p' node
const p = document.getElementById("p2");
// moves it to the end of 'body'
b.appendChild(p);
}
</script>
</head>
<body id="body">
<p id="p1" style="background: aqua">one</p>
<p id="p2" style="background: green">two</p>
<p id="p3" style="background: red">three</p>
<button onclick="go()">Move the second paragraph</button>
</body>
</html>
當點選按鈕時,函式 go 被呼叫。它訪問元素 'body' 和 'p2',然後將 'p' 元素移動到 'body' 的末尾。