aboutsummaryrefslogtreecommitdiff
path: root/files/vi/web/api/document_object_model/introduction/index.html
blob: 7a1ef163ee023c36aece4d17a687701f27518d7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
---
title: Introduction to the DOM
slug: Web/API/Document_Object_Model/Introduction
translation_of: Web/API/Document_Object_Model/Introduction
---
<p>Phần này cung cấp một giới thiệu khái niệm ngắn gọn về <a href="https://developer.mozilla.org/en-US/docs/DOM" title="DOM">DOM</a>: nó là gì, nó cung cấp cấu trúc cho HTML và XML như thế nào, bạn có thể truy cập nó thế nào, và API này trình bày thông tin và các ví dụ tham khảo.</p>

<h2 id="What_is_the_DOM" name="What_is_the_DOM">DOM là gì?</h2>

<p>The Document Object Model (DOM) là một giao diện lập trình cho tài liệu HTML và XML. Nó cung cấp đại diện cấu trúc của tài liệu và nó xác định con đường mà cấu trúc có thể được truy cập từ các chương trình để chúng có thể thay đổi cấu trúc, phong cách và nội dung tài liệu. DOM cung cấp một sự trình bày của tài liệu như một nhóm cấu trúc của các nút và đối tượng mà có các thuộc tính và phương thức. Về cơ bản, nó kết nối các trang web tới các đoạn mã hay các ngôn ngữ lập trình.</p>

<p>Một trang Web là một tài liệu. Tài liệu này có thể hoặc là được hiển thị trong cửa sổ trình duyệt hoặc là như mã nguồn HTML. Nhưng nó cùng là tài liệu trong cả hai trường hợp. The Document Object Model (DOM) cung cấp cách khác để hiển thị, lưu trữ và thao tác cùng tài liệu. DOM là một đại diện hướng đối tượng hoàn toàn của trang web, và nó có thể được chỉnh sửa với một ngôn ngữ kịch bản như JavaScript.</p>

<p>Các tiêu chuẩn <a class="external" href="http://www.w3.org/DOM/">W3C DOM</a> và <a class="external" href="https://dom.spec.whatwg.org">WHATWG DOM</a> tạo thành nền tảng của DOM được thực hiện trong hầu hết các trình duyệt hiện đại . Nhiều trình duyệt cung cấp các mở rộng bên ngoài chuẩn, nên phải cẩn thận khi sử dụng chúng trên web nơi các tài liệu có thể được truy cập bởi các trình duyệt khác nhau với các DOM khác nhau.</p>

<p>Ví dụ, DOM chuẩn quy định rằng phương thức getElementsByTagName trong code bên dưới phải trả về một danh sách của tất cả phần tử &lt;p&gt; trong tài liệu:</p>

<pre class="brush: js">var paragraphs = document.getElementsByTagName("P");
// paragraphs[0] is the first &lt;p&gt; element
// paragraphs[1] is the second &lt;p&gt; element, etc.
alert(paragraphs[0].nodeName);
</pre>

<p>Tất cả các thuộc tính, phương thức và sự kiện được sử dụng để thao tác và tạo ra các trang web được tổ chức dưới dạng các đối tượng (objects) (vd: đối tượng <code>document</code> đại diện cho trang tài liệu, đối tượng <code>table</code> kế thừa từ <code>HTMLTableElement</code>, một DOM interface đặc thù, cho phép truy cập HTML tables, v.v...). Phần này sẽ giới thiệu từng đối tượng DOM, được kế thừa trong các trình duyệt chạy trên nền Gecko.</p>

<h2 id="DOM_and_JavaScript" name="DOM_and_JavaScript">DOM and JavaScript</h2>

<p>The short example above, like nearly all of the examples in this reference, is <a href="/en-US/docs/JavaScript" title="JavaScript">JavaScript</a>. That is to say, it's <em>written</em> in JavaScript, but it <em>uses</em> the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). Every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.</p>

<p>In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:</p>

<p>API (HTML or XML page) = DOM + JS (scripting language)</p>

<p>The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though we focus exclusively on JavaScript in this reference documentation, implementations of the DOM can be built for any language, as this Python example demonstrates:</p>

<pre class="brush: 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");
</pre>

<p>For more information on what technologies are involved in writing JavaScript on the web, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p>

<h2 id="How_Do_I_Access_the_DOM.3F" name="How_Do_I_Access_the_DOM.3F">How Do I Access the DOM?</h2>

<p>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.</p>

<p>When you create a script–whether it's inline in a <code>&lt;script&gt;</code> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the <code><a href="/en-US/docs/DOM/document" title="DOM/document">document</a></code> or <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> 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 <code><a href="/en-US/docs/DOM/window.alert" title="DOM/window.alert">alert()</a></code> function from the <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.</p>

<pre class="brush: html">&lt;body onload="window.alert('Welcome to my home page!');"&gt;
</pre>

<p>Aside from the <code>&lt;script&gt;</code> 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 <code>H1</code> to the tree for this document:</p>

<pre class="brush: html">&lt;html&gt;
  &lt;head&gt;
    &lt;script&gt;
       // run this function when the document is loaded
       window.onload = function() {

         // create a couple of elements in an otherwise empty HTML page
         var heading = document.createElement("h1");
         var heading_text = document.createTextNode("Big Head!");
         heading.appendChild(heading_text);
         document.body.appendChild(heading);
      }
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>

<h2 id="Important_Data_Types" name="Important_Data_Types">Important Data Types</h2>

<p>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 <code>element</code>s, to arrays of nodes as <code>nodeList</code>s (or simply <code>element</code>s), and to <code>attribute</code> nodes simply as <code>attribute</code>s.</p>

<p>The following table briefly describes these data types.</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td><code>document</code></td>
   <td>When a member returns an object of type <code>document</code> (e.g., the <strong><code>ownerDocument</code></strong> property of an element returns the <code>document</code> to which it belongs), this object is the root <code>document</code> object itself. The <a href="/en-US/docs/DOM/document" title="DOM/document">DOM <code>document</code> Reference</a> chapter describes the <code>document</code> object.</td>
  </tr>
  <tr>
   <td><code>element</code></td>
   <td><code>element</code> refers to an element or a node of type <code>element</code> returned by a member of the DOM API. Rather than saying, for example, that the <a href="/en-US/docs/Web/API/Document/createElement">document.createElement()</a> method returns an object reference to a <code>node</code>, we just say that this method returns the <code>element</code> that has just been created in the DOM. <code>element</code> objects implement the DOM <code>Element</code> interface and also the more basic <code>Node</code> interface, both of which are included together in this reference.</td>
  </tr>
  <tr>
   <td><code>nodeList</code></td>
   <td>A <code>nodeList</code> is an array of elements, like the kind that is returned by the method <a href="/en-US/docs/Web/API/Document/getElementsByTagName">document.getElementsByTagName()</a>. Items in a <code>nodeList</code> are accessed by index in either of two ways:
    <ul>
     <li>list.item(1)</li>
     <li>list[1]</li>
    </ul>
    These two are equivalent. In the first, <strong><code>item()</code></strong> is the single method on the <code>nodeList</code> object. The latter uses the typical array syntax to fetch the second item in the list.</td>
  </tr>
  <tr>
   <td><code>attribute</code></td>
   <td>When an <code>attribute</code> is returned by a member (e.g., by the <strong><code>createAttribute()</code></strong> 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.</td>
  </tr>
  <tr>
   <td><code>namedNodeMap</code></td>
   <td>A <code>namedNodeMap</code> 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 <code>namedNodeMap</code> has an item() method for this purpose, and you can also add and remove items from a <code>namedNodeMap</code>.</td>
  </tr>
 </tbody>
</table>

<h2 id="DOM_interfaces" name="DOM_interfaces">DOM interfaces</h2>

<p>This guide is about the objects and the actual <em>things</em> you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the <code>HTML form</code> element gets its <strong><code>name</code></strong> property from the <code>HTMLFormElement</code> interface but its <strong><code>className</code></strong> property from the <code>HTMLElement</code> interface proper. In both cases, the property you want is simply in that form object.</p>

<p>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.</p>

<h3 id="Interfaces_and_Objects" name="Interfaces_and_Objects">Interfaces and Objects</h3>

<p>Many objects borrow from several different interfaces. The table object, for example, implements a specialized <a href="/en-US/docs/DOM/HTMLTableElement" title="DOM/table">HTML Table Element Interface</a>, which includes such methods as <code>createCaption</code> and <code>insertRow</code>. But since it's also an HTML element, <code>table</code> implements the <code>Element</code> interface described in the <a href="/en-US/docs/DOM/element" title="DOM/element">DOM <code>element</code> Reference</a> 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 an HTML or XML page, the table element also implements the more basic <code>Node</code> interface, from which <code>Element</code> derives.</p>

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

<pre class="brush: js">var table = document.getElementById("table");
var tableAttrs = table.attributes; // Node/Element interface
for (var i = 0; i &lt; 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";
</pre>

<h3 id="Core_Interfaces_in_the_DOM" name="Core_Interfaces_in_the_DOM">Core Interfaces in the DOM</h3>

<p>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 <a href="/en-US/docs/Gecko_DOM_Reference/Examples" title="Gecko_DOM_Reference/Examples">DOM Examples</a> chapter at the end of this book.</p>

<p><code>Document</code> and <code>window</code> objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the <code>window</code> object represents something like the browser, and the <code>document</code> object is the root of the document itself. <code>Element</code> inherits from the generic <code>Node</code> 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 <code>table</code> object example in the previous section.</p>

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

<ul>
 <li><code><a href="/en-US/docs/DOM/document.getElementById" title="DOM/document.getElementById">document.getElementById</a>(id)</code></li>
 <li><code>document.<a href="/en-US/docs/Web/API/Element.getElementsByTagName" title="DOM/element.getElementsByTagName">getElementsByTagName</a>(name)</code></li>
 <li><code><a href="/en-US/docs/DOM/document.createElement" title="DOM/document.createElement">document.createElement</a>(name)</code></li>
 <li><code>parentNode.<a href="/en-US/docs/DOM/Node.appendChild" title="DOM/Node.appendChild">appendChild</a>(node)</code></li>
 <li><code>element.<a href="/en-US/docs/DOM/element.innerHTML" title="DOM/element.innerHTML">innerHTML</a></code></li>
 <li><code>element.<a href="/en-US/docs/DOM/element.style" title="DOM/element.style">style</a>.left</code></li>
 <li><code>element.<a href="/en-US/docs/DOM/element.setAttribute" title="DOM/element.setAttribute">setAttribute</a></code></li>
 <li><code>element.<a href="/en-US/docs/DOM/element.getAttribute" title="DOM/element.getAttribute">getAttribute</a></code></li>
 <li><code>element.<a href="/en-US/docs/DOM/element.addEventListener" title="DOM/element.addEventListener">addEventListener</a></code></li>
 <li><code><a href="/en-US/docs/DOM/window.content" title="DOM/window.content">window.content</a></code></li>
 <li><code><a href="/en-US/docs/DOM/window.onload" title="DOM/window.onload">window.onload</a></code></li>
 <li><code><a href="/en-US/docs/DOM/window.dump" title="DOM/window.dump">window.dump</a></code></li>
 <li><code><a href="/en-US/docs/DOM/window.scrollTo" title="DOM/window.scrollTo">window.scrollTo</a></code></li>
</ul>

<h2 id="Testing_the_DOM_API" name="Testing_the_DOM_API">Testing the DOM API</h2>

<p>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 <code>&lt;script&gt;</code> 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.</p>

<p>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 <code>&lt;script&gt;</code> 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.</p>

<p>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 <code>test()</code> function as needed, create more buttons, or add elements as necessary.</p>

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

<p>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.</p>

<figure>
<figcaption>Figure 0.1 Sample DOM Test Page</figcaption>
<img alt="Image:DOM_Ref_Introduction_to_the_DOM.gif" class="internal" src="/@api/deki/files/173/=DOM_Ref_Introduction_to_the_DOM.gif"></figure>

<p>In this example, the dropdown menus dynamically update such DOM-accessible aspects of the web page as its background color (<code>bgColor</code>), the color of the hyperlinks (<code>aLink</code>), and color of the text (<code>text</code>). 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.</p>

<h2 id="Subnav">Subnav</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a></li>
 <li><a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">Introduction to the DOM</a></li>
 <li><a href="/en-US/docs/Web/API/Document_Object_Model/Events">Events and the DOM</a></li>
 <li><a href="/en-US/docs/Web/API/Document_Object_Model/Examples">Examples</a></li>
</ul>