使用文件物件模型
文件物件模型 (DOM) 是一個用於操作 HTML 和 XML 文件 (以及其他樹狀文件) 的 DOM 樹的 API。此 API 是頁面描述的根源,是 Web 指令碼的基礎。
什麼是 DOM 樹?
DOM 樹是一種樹狀結構,其節點表示 HTML 或 XML 文件的內容。每個 HTML 或 XML 文件都具有 DOM 樹表示。例如,考慮以下文件
html
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
它有一個看起來像這樣的 DOM 樹
儘管上面的樹與上面文件的 DOM 樹相似,但並不完全相同,因為實際的 DOM 樹保留了空格.
當 Web 瀏覽器解析 HTML 文件時,它會構建一個 DOM 樹,然後使用它來顯示文件。
文件 API 有什麼作用?
文件 API (有時也稱為 DOM API) 允許您以任何您想要的方式修改 DOM 樹。它使您可以從頭開始建立任何 HTML 或 XML 文件,或者更改給定 HTML 或 XML 文件的任何內容。網頁作者可以使用 JavaScript 編輯文件的 DOM,以訪問全域性物件的document 屬性。此document 物件實現了Document 介面。
讀取和修改樹
假設作者想要更改上面文件的標題,並編寫兩個段落而不是一個。以下指令碼將完成這項工作
HTML
html
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<input type="button" value="Change this document." onclick="change()" />
<h2>Header</h2>
<p>Paragraph</p>
</body>
</html>
JavaScript
js
function change() {
// document.getElementsByTagName("h2") returns a NodeList of the <h2>
// elements in the document, and the first is number 0:
const header = document.getElementsByTagName("h2").item(0);
// The firstChild of the header is a Text node:
header.firstChild.data = "A dynamic document";
// Now header is "A dynamic document".
// Access the first paragraph
const para = document.getElementsByTagName("p").item(0);
para.firstChild.data = "This is the first paragraph.";
// Create a new Text node for the second paragraph
const newText = document.createTextNode("This is the second paragraph.");
// Create a new Element to be the second paragraph
const newElement = document.createElement("p");
// Put the text in the paragraph
newElement.appendChild(newText);
// Put the paragraph on the end of the document by appending it to
// the body (which is the parent of para)
para.parentNode.appendChild(newElement);
}
建立樹
您也可以在 JavaScript 中完全建立上面的樹。
js
const root = document.createElement("html");
root.lang = "en";
const head = document.createElement("head");
const title = document.createElement("title");
title.appendChild(document.createTextNode("My Document"));
head.appendChild(title);
const body = document.createElement("body");
const header = document.createElement("h1");
header.appendChild(document.createTextNode("Header"));
const paragraph = document.createElement("p");
paragraph.appendChild(document.createTextNode("Paragraph"));
body.appendChild(header);
body.appendChild(paragraph);
root.appendChild(head);
root.appendChild(body);
如何瞭解更多資訊?
現在您已經熟悉了 DOM 的基本概念,您可能想要閱讀如何使用 JavaScript 和 DOM 介面遍歷 HTML 表格,以瞭解有關文件 API 的更多基本功能。
另請參閱
- 文件物件模型 (DOM).