每一份載入瀏覽器的 HTML 文件,都會被包裝成一個 Document 物件。透過它,我們就能用腳本隨意讀取與操作頁面上的元素,可以說是進入 DOM 世界的第一道門。
document.anchors:回傳文件中所有 Anchor 物件的集合,同類型的還有 document.links、document.forms、document.images 等。document.URL:回傳目前文件的網址。document.title:讀取或設定文件標題。document.body:取得 body 元素節點。搭配 document.open() 使用,用來關閉輸出流並把寫入的內容顯示出來。
<!DOCTYPE html>
<html>
<head>
<script>
function createDoc() {
var w = window.open();
w.document.open();
w.document.write("<h1>Hello World!</h1>");
w.document.close();
}
</script>
</head>
<body>
<input type="button" value="New document in a new window" onclick="createDoc()">
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<p>hello world</p>
<script>
var a = document.createElement('hr');
document.body.appendChild(a);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to make a BUTTON element.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
document.body.appendChild(btn);
};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<p>hello world</p>
<script>
var a = document.createTextNode('hahahah');
document.body.appendChild(a);
</script>
</body>
</html>
回傳文件中所有指定 class 名的元素集合,型別是 NodeList。NodeList 是「類陣列」結構,只有 length 屬性可用,並不提供 push、pop 這類陣列方法。
回傳第一個符合指定 id 的物件。
回傳所有 name 屬性相符的物件集合。
回傳所有指定標籤名的物件集合。
直接把 HTML 敘述或 JavaScript 字串寫進文件。這裡有個大坑:當 HTML 文件已經載入完成後再呼叫 write,會把原本的內容整個覆蓋掉,因此盡量只在載入階段使用,或改用 DOM 操作 API。
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<p>hello world</p>
<script>
document.write('hahahh');
</script>
</body>
</html>
把這些屬性與方法摸熟,日常的頁面元素操作基本就夠用了;進階一點的開發則建議改用 querySelector 系列 API,表達力更強也更靈活。