
因此整份 HTML 文件就是一個文件樹 (DOM tree) ,我們可以利用 JavaScript 對文件進行處理,例如下面的網頁檔案設置一個 RUN 按鈕,按下 RUN 之後,在 RUN 的下方會新增一個 <div> 元素,其內為 There is no spoon. 的字串
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 DEMO</title>
<style>
article {
display: block;
}
</style>
<script>
function run() {
var d = document.getElementById("demo");
var n = document.createElement("div");
n.innerHTML = "There is no spoon.";
d.appendChild(n);
}
</script>
</head>
<body>
<section>
<article id="demo">
<div><input type="button" value="RUN" onclick="run();"></div>
</article>
</section>
</body>
</html>
<!-- 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:domtest1.html
功能:示範 HTML 5 標記語言
作者:張凱慶
時間:西元 2011 年 12 月 -->Firefox 開啟,按 RUN 後的結果如下

此例是利用 document 的 getElementById() 方法 (method) 取得 <article> 元素,然後再以 createElement() 新建一個 <div> 元素物件,並將 <div> 物件的 innerHTML 屬性 (attribute) 設定為 "There is no spoon." ,最後利用 <article> 元素物件的 appendChild() 方法將 <div> 加進 <article> 內,預設會接在 <article> 所有子代物件的最後,因此會顯示在 RUN 的下方。
我們也可以反過來,把 There is no spoon. 放在 RUN 的上方,例如
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 DEMO</title>
<style>
article {
display: block;
}
</style>
<script>
function run() {
var d = document.getElementById("demo");
var p = d.parentNode;
var n = document.createElement("article");
n.innerHTML = "There is no spoon.";
p.insertBefore(n, d);
}
</script>
</head>
<body>
<section>
<article id="demo">
<div><input type="button" value="RUN" onclick="run();"></div>
</article>
</section>
</body>
</html>
<!-- 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:domtest2.html
功能:示範 HTML 5 標記語言
作者:張凱慶
時間:西元 2011 年 12 月 -->Firefox 開啟,按 RUN 後的結果如下

這個例子是利用元素物件的 parentNode 屬性取得親代 <section> 物件,然後將新建的 <article> 插入 RUN 的 <article> 之前。
利用文件樹便可輕易的操作 HTML 網頁的元素,相關內容可參考本站的《HTML DOM 快速導覽》。
| 中英文術語對照 | |
|---|---|
| 物件 | object |
| 元素 | element |
| 方法 | method |
| 屬性 | attribute |
| 瀏覽器 | broswer |
您可以繼續參考
基本概念
相關目錄
HTML 5 快速導覽
HTML, CSS 教材
首頁
參考資料
http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#dom-trees
http://www.w3.org/TR/2011/WD-html5-20110525/infrastructure.html#dom-trees
http://en.wikipedia.org/wiki/DOM_tree
沒有留言:
張貼留言