Visit Mozilla.org

Gecko DOM 参考:入门

From MDC

« Gecko DOM 参考

This section provides a brief conceptual introduction to the DOM: what it is, how it provides structure for HTML and XML documents, how you can access it, and how this API presents the reference information and examples.

目录

[编辑] DOM是什么?

Document Object Model (DOM)是HTML和XML文档的编程接口。它提供了上述文档的一种结构化表示,同时也定义了一种通过程序来改变文档结构,风格,以及内容的方式。DOM用一组结构化的节点以及对象来表示文档。本质上就是将网页和脚本语言以及编程语言连接起来。

一个网页是一个文档。这个文档可以被显示在浏览器窗口中,也可以以html源码的形式显示。这两中情况中,文档都是同一个。DOM提供了另一种方式来表示,存储,操作这个文档。DOM是网页的一种完全的面向对象的表示方法,可以通过脚本语言(比如说JavaScript)来改变。

W3C DOM标准形成了当今大多数浏览器的DOM基础。许多浏览器提供超出W3C标准的扩展,所以当用在可能被拥有不同DOM的各种浏览器使用的场合时 一定要多加注意

例如,W3C DOM规定在以下代码中的getElementsByTagName方法必须返回一个包含文档中所有<P>元素的列表:

paragraphs = document.getElementsByTagName("P");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);

所有可以用来维护和创建web页面的属性、方法和事件都被组织到对象中(例如,document对象代表文档自身,table对象则实现了特殊的HTMLTableElement DOM接口以访问HTML表格,诸如此类)。本文档提供Gecko内核浏览器所实现的DOM各对象参考。

[编辑] DOM 和 JavaScript

上面这个简短的例子,像这份参考中几乎所有的例子那样,是JavaScript。也就是说,她是用JavaScript编写的,但是她使用DOM访问文档和它的元素。DOM不是一门编程语言,但是没有她,JavaScript就无法把握网页的概念模型,XML页面以及经常涉及的元素。文档中的每个元素——整个文档,她的头部,文档中的表格,表格的标题,以及表格单元格中的文本——是这个文档的文档对象模型的一部分,所以他们可以被DOM和像JavaScript这样的脚本语言访问和处理。

在开始阶段,JavaScript和DOM是紧密的联系在一起的,但是最终他们将发展为独立的实体。网页的内容存储在DOM中并且可以被JavaScript访问和处理,所以我们可以得到写下这个近似的等式:

API(网页或者XML页面)=DOM + JS(脚本语言)

DOM被设计为独立于任何特定的编程语言,通过协调一致的API以确保这种文档的结构化表现形式是有效的。虽然在这份参考文档中我们专注于JavaScript,但是DOM的实现可以建立在任何语言上,像如下面这个Python的例子演示:


# Python DOM example
import xml.dom.minidom as m
doc = m.parse("C:\\Projects\\Py\\chap1.xml");
doc.nodeName # DOM property of document object;
p_list = doc.getElementsByTagName("para");

[编辑] 我如何访问DOM?

You don't have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible to script. 你不必要做一些特殊的准备去使用DOM。不同的浏览器有不同的DOM实现,这些实现在不同的程度上遵从W3C的DOM标准(对于这个主题本文档避开不谈)。但是每个浏览器uses some document object model to make web pages accessible to script.


When you create a script–whether it's in-line in a <SCRIPT> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.

<body onload="window.alert('welcome to my home page!');">

Aside from the <script> element in which the JavaScript is defined, this JavaScript sets a function to run when the document is loaded (and when the whole DOM is available for use). This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document:

<html>
<head>
<script>
// run this function when the document is loaded
window.onload = function() {
   // create a couple of elements 
   // in an otherwise empty HTML page
   heading = document.createElement("h1");
   heading_text = document.createTextNode("Big Head!");
   heading.appendChild(heading_text);
   document.body.appendChild(heading);
}
</script>
</head>
<body>
</body>
</html>

[编辑] 重要的数据类型

This reference tries to describe the various objects and types in as simple a way as possible. But there are a number of different data types being passed around the API that you should be aware of. For the sake of simplicity, syntax examples in this API reference typically refer to nodes as elements, to arrays of nodes as nodeLists (or simply elements), and to attribute nodes simply as attributes.

The following table briefly describes these data types.

document When a member returns an object of type document (e.g., the ownerDocument property of an element returns the document to which it belongs), this object is the root document object itself. The DOM document Reference chapter describes the document object.
element element refers to an element or a node of type element returned by a member of the DOM API. Rather than saying, for example, that the document.createElement() method returns an object reference to a node, we just say that this method returns the element that has just been created in the DOM. element objects implement the DOM Element interface and also the more basic Node interface, both of which are included together in this reference.
nodeList A nodeList is an array of elements, like the kind that is returned by the method document.getElementsByTagName(). Items in a nodeList are accessed by index in either of two ways:
  • list.item(1)
  • list[1]

These two are equivalent. In the first, item() is the single method on the nodeList object. The latter uses the typical array syntax to fetch the second item in the list.

attribute When an attribute is returned by a member (e.g., by the createAttribute() method), it is an object reference that exposes a special (albeit small) interface for attributes. Attributes are nodes in the DOM just like elements are, though you may rarely use them as such.
NamedNodeMap A namedNodeMap is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list. A NamedNodeMap has an item() method for this purpose, and you can also add and remove items from a NamedNodeMap

[编辑] DOM 接口

A stated purpose of this guide is to minimize talk about abstract interfaces, inheritance, and other implementation details, and to talk instead about the objects in the DOM, about the actual things you can use to manipulate the DOM hierarchy. From the point of view of the web programmer, it's often a matter of indifference that the object representing the HTML FORM element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface proper. In both cases, the property you want is simply in the form object.

But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

[编辑] Interfaces and Objects

In some cases, an object implements a single interface. But more often than not, an object like a HTML table borrow from several different interfaces. The table object, for example, implements a specialized HTML Table Element Interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for a web page or an XML page, the table element also implements the more basic Node interface, from which Element derives.

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

var table = document.getElementById("table");
var tableAttrs = table.attributes; // Node/Element interface
for(var i = 0; i < tableAttrs.length; i++){
  // HTMLTableElement interface: border attribute
  if(tableAttrs[i].nodeName.toLowerCase() == "border")
    table.border = "1"; 
}
// HTMLTableElement interface: summary attribute
table.summary = "note: increased border";

[编辑] Core Interfaces in the DOM

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

Document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

The following is a brief list of common APIs in web and XML page scripting using the DOM.

[编辑] 测试 DOM API

This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser.

There are some cases, however, when the examples are more concise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to call those functions from the browser.

You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the test() function as needed, create more buttons, or add elements as necessary.

<html>
<head>
<title>DOM Tests</title>
<script type="application/x-javascript">
function setBodyAttr(attr,value){
  if(document.body) eval('document.body.'+attr+'="'+value+'"');
  else notSupported();
}
</script>
</head> 
<body>
<div style="margin: .5in; height="400""> 
<p><b><tt>text</tt> color</p> 
<form> 
<select onChange="setBodyAttr('text',
    this.options[this.selectedIndex].value);"> 
<option value="black">black 
<option value="darkblue">darkblue 
</select>
 <p><b><tt>bgColor</tt></p>
 <select onChange="setBodyAttr('bgColor',
    this.options[this.selectedIndex].value);"> 
<option value="white">white 
<option value="lightgrey">gray
 </select>
<p><b><tt>link</tt></p> 
<select onChange="setBodyAttr('link',
     this.options[this.selectedIndex].value);">
<option value="blue">blue
<option value="green">green
</select>  <small>
     <a href="http://www.brownhen.com/dom_api_top.html" id="sample">
(sample link)</a></small><br>
</form>
<form>
  <input type="button" value="version" onclick="ver()" />
</form>
</div>
</body>
</html>

To test a lot of interfaces in a single page-for example, a "suite" of properties that affect the colors of a web page-you can create a similar test page with a whole console of buttons, textfields, and other HTML elements. The following screenshot gives you some idea of how interfaces can be grouped together for testing.

Image:DOM Ref Introduction to the DOM.gif
Figure 0.1 Sample DOM Test Page

In this example, the dropdown menus dynamically update such DOM-accessible aspects of the web page as its background color (bgColor), the color of the hyperlinks (aLink), and color of the text (text). However you design your test pages, testing the interfaces as you read about them is an important part of learning how to use the DOM effectively.