本文檔對象模型允許訪問所有的文檔內容和修改,由萬維網聯合會(W3C)規範。幾乎所有的現代流覽器都支持這種模式。
在W3C DOM規範的大部分傳統DOM的功能,而且還增加了新的重要的功能。除了支持forms[ ], images[ ]和文檔對象的其他數組屬性,它定義了方法,使腳本來訪問和操縱的任何文檔元素,而不只是專用元件狀的表單和圖像。
文檔屬性在W3C DOM:
此模型支持所有傳統DOM提供的屬性。此外,這裏是文檔屬性,可以使用W3C DOM訪問列表:
| 屬性 | 介紹和示例 |
|---|---|
| body |
引用元素對象,表示該檔的<body>標籤 示例: document.body |
| defaultView |
其只讀屬性,並表示在其上顯示所述文檔的窗口 示例: document.defaultView |
| documentElement |
只讀參考檔的<html>標籤 示例: document.documentElement8/31/2008 |
| implementation |
其只讀屬性,代表了DOMImplementation的對象,表示創建該檔的實現 示例: document.implementation |
文檔方法在W3C DOM:
此模型支持所有傳統DOM提供的方法。此外,這裏是由W3C DOM支持的方法列表:
| 方法 | 介紹和示例 |
|---|---|
| createAttribute( name) |
返回具有指定名稱的新創建的Attr節點 示例: document.createAttribute( name) |
| createComment( text) |
創建並返回包含指定文本的新注釋節點 示例: document.createComment( text) |
| createDocumentFragment( ) |
創建並返回一個空的DocumentFragment節點 示例: document.createDocumentFragment( ) |
| createElement( tagName) |
創建並返回指定標籤名稱的新元素節點 示例: document.createElement( tagName) |
| createTextNode( text) |
創建並返回包含指定文本的新文本節點 示例: document.createTextNode( text) |
| getElementById( id) |
返回此檔有其id屬性指定的值,或空,如果沒有這樣的元素存在於文檔中的元素 示例: document.getElementById( id) |
| getElementsByName( name) |
返回的文檔中有自己的名字屬性的指定值的所有元素的節點的數組。如果沒有找到這樣的元素,則返回一個零長度數組 示例: document.getElementsByName( name) |
| getElementsByTagName( tagname) |
返回具有指定標籤名本文檔中的所有元素節點的數組。元素節點出現在他們出現在原始檔案相同的順序返回數組中 示例: document.getElementsByTagName( tagname) |
| importNode( importedNode, deep) |
創建並從其他檔是適於插入到本文檔返回節點的副本。如果參數deep是true,它遞歸拷貝節點的子節點。支持DOM2版 示例: document.importNode( importedNode, deep) |
示例:
這是(訪問和設置)使用W3C DOM文檔元素很容易操縱。可以使用任何類似 getElementById,getElementsByName,orgetElementsByTagName 方法。
下麵是訪問使用W3C DOM方法文檔屬性的一個例子:
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
<!--
function myFunc()
{
var ret = document.getElementsByTagName("title");
alert("Document Title : " + ret[0].text );
var ret = document.getElementById("heading");
alert(ret.innerHTML );
}
//-->
</script>
</head>
<body>
<h1 id="heading">This is main title</h1>
<p>Click the following to see the result:</p>
<form id="form1" name="FirstForm">
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
<form d="form2" name="SecondForm">
<input type="button" value="Don't ClickMe"/>
</form>
</body>
</html>
注意: 這個例子的形式和內容等返回對象,我們將不得不使用未在本教學中討論這些對象的屬性來訪問它們的值。
上一篇:
JavaScript傳統DOM
下一篇:
JavaScript IE4 DOM
