mozilla

Revision 171887 of Introduction

  • Slug da revisão: Gecko_DOM_Reference/Introduction
  • Título da revisão: Introduction
  • ID da revisão: 171887
  • Criado:
  • Autor: Davis.peixoto
  • É revisão atual? Não
  • Comentário

Conteúdo da revisão

{{template.DomRef()}}

Esta seção provê uma breve introdução conceitual ao DOM: o que ele é, como ele provê estruturas para documentos HTML e XML, como você pode acessá-lo, e como esta API apresenta informações de referência e exemplos.

O que é o DOM?

O Document Object Model (DOM) é uma interface de programação para documentos HTML e XML. Ele provê uma representação estruturada do documento e define um meio pelo qual a estrutura pode ser acessada por programas permitindo-os alterar a estrutura do documento, estilo e conteúdo. O DOM provê uma representação do documento como um conjunto estruturado de nós e objetos que têm propriedades e métodos. Essencialmente ele conecta páginas de internet a scripts ou linguagens de programação.

Uma página de internet é um documento. Este documento pode ser exibido numa janela de navegador, ou como código-fonte HTML. Mas é o mesmo documento em ambos os casos. O Document Object Model (DOM) provê uma outra forma de representar, armazenar e manipular o mesmo documento. O DOM é uma representação orientada a objeto completa da página, e pode ser modificada com uma linguagem de script como o JavaScript.

O padrão W3C DOM constitui as bases para a implementação do DOM nos mais modernos navegadores. Muitos navegadores oferecem extensões que vão além do padrão W3C, portanto a cautela deve ser exercida quando do seu uso em páginas onde os documentos podem ser acessados por vários navegadores com diferentes implementações do DOM.

Por exemplo, o DOM W3C especifica que o método getElementsByTagName no código abaixo deve retornar uma lista com todos os elementos <P> contidos no documento:

paragraphs = document.getElementsByTagName("P");
// paragraphs[0] é o primeiro elemento <p>
// paragraphs[1] é o segundo elemento <p>, etc.
alert(paragraphs[0].nodeName);

Todas as propriedades, métodos, e eventos disponíveis para manipular e criar páginas estão organizados em objetos (por exemplo, o objeto document representa o próprio documento, o objeto table implementa a interface DOM HTMLTableElement para acessar tabelas HTML, e assim por diante). Esta documentação dispõe uma referência objeto a objeto para o DOM implementado nos navegadores baseados no Gecko.

DOM e JavaScript

O rápido exemplo acima, parecido com a maioria dos exemplos desta referência, é JavaScript. Ou seja, ele foi escrito em JavaScript, mas ele usa o DOM para acessar o documento e seus elementos. O DOM não é uma linguagem de programação, mas sem ele, a linguagem JavaScript não teria nenhum modelo ou noção de páginas web, páginas XML e elementos com os quais ela geralmente lida. Todo elemento num documento—o documento como um todo, o cabeçalho, tabelas dentro do documento, cabeçalhos de tabelas, o texto dentro das células— faz parte do document object model para aquele documento, portanto eles podem ser acessados e manipulados fazendo-se uso do DOM e de uma linguagem de scripting como o JavaScript.

No início, JavaScript e o DOM eram fortemente ligados, mas eventualmente evoluíram em entidades separadas. O conteúdo da página é armazenado no DOM e pode ser acessado e manipulado via JavaScript, portanto nós podemos escrever esta equação aproximativa:

API(web ou página XML) = DOM + JS(linguagem de scripting)

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:

# 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");

How Do I Access the 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.

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>

Important Data Types

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{{mediawiki.external(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 Interfaces

This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. 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

Many objects 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.

Testing the 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.

{{ wiki.languages( { "en": "en/Gecko_DOM_Reference/Introduction", "fr": "fr/R\u00e9f\u00e9rence_du_DOM_Gecko/Introduction", "ja": "ja/Gecko_DOM_Reference/Introduction", "pl": "pl/Dokumentacja_Gecko_DOM/Wprowadzenie", "zh-cn": "cn/Gecko_DOM_\u53c2\u8003/\u5165\u95e8", "es": "es/Referencia_DOM_de_Gecko/Introducci\u00f3n" } ) }}

Fonte da revisão

<p>
{{template.DomRef()}}
</p><p>Esta seção provê uma breve introdução conceitual ao DOM: o que ele é, como ele provê estruturas para documentos <a href="pt/HTML">HTML</a> e <a href="pt/XML">XML</a>, como você pode acessá-lo, e como esta API apresenta informações de referência e exemplos.
</p>
<h3 name="O_que_.C3.A9_o_DOM.3F">O que é o DOM?</h3>
<p>O Document Object Model (DOM) é uma interface de programação para documentos HTML e XML. Ele provê uma representação estruturada do documento e define um meio pelo qual a estrutura pode ser acessada por programas permitindo-os alterar a estrutura do documento, estilo e conteúdo. O DOM provê uma representação do documento como um conjunto estruturado de nós e objetos que têm propriedades e métodos. Essencialmente ele conecta páginas de internet a scripts ou linguagens de programação.
</p><p>Uma página de internet é um documento. Este documento pode ser exibido numa janela de navegador, ou como código-fonte HTML. Mas é o mesmo documento em ambos os casos. O Document Object Model (DOM) provê uma outra forma de representar, armazenar e manipular o mesmo documento. O DOM é uma representação orientada a objeto completa da página, e pode ser modificada com uma linguagem de script como o JavaScript.
</p><p>O padrão <a class="external" href="http://www.w3.org/DOM/">W3C DOM</a> constitui as bases para a implementação do DOM nos mais modernos navegadores. Muitos navegadores oferecem extensões que vão além do padrão W3C, portanto a cautela deve ser exercida quando do seu uso em páginas onde os documentos podem ser acessados por vários navegadores com diferentes implementações do DOM.
</p><p>Por exemplo, o DOM W3C especifica que o método <code>getElementsByTagName</code> no código abaixo deve retornar uma lista com todos os elementos <code>&lt;P&gt;</code> contidos no documento:
</p>
<pre>paragraphs = document.getElementsByTagName("P");
// paragraphs[0] é o primeiro elemento &lt;p&gt;
// paragraphs[1] é o segundo elemento &lt;p&gt;, etc.
alert(paragraphs[0].nodeName);
</pre>
<p>Todas as propriedades, métodos, e eventos disponíveis para manipular e criar páginas estão organizados em objetos (por exemplo, o objeto <code>document</code> representa o próprio documento, o objeto <code>table</code> implementa a interface DOM <code>HTMLTableElement</code> para acessar tabelas HTML, e assim por diante). Esta documentação dispõe uma referência objeto a objeto para o DOM implementado nos navegadores baseados no Gecko.
</p>
<h3 name="DOM_e_JavaScript">DOM e JavaScript</h3>
<p>O rápido exemplo acima, parecido com a maioria dos exemplos desta referência, é <a href="pt/JavaScript">JavaScript</a>. Ou seja, ele foi <i>escrito</i> em JavaScript, mas ele <i>usa</i> o DOM para acessar o documento e seus elementos. O DOM não é uma linguagem de programação, mas sem ele, a linguagem JavaScript não teria nenhum modelo ou noção de páginas web, páginas XML e elementos com os quais ela geralmente lida. Todo elemento num documento—o documento como um todo, o cabeçalho, tabelas dentro do documento, cabeçalhos de tabelas, o texto dentro das células— faz parte do document object model para aquele documento, portanto eles podem ser acessados e manipulados fazendo-se uso do DOM e de uma linguagem de scripting como o JavaScript.
</p><p>No início, JavaScript e o DOM eram fortemente ligados, mas eventualmente evoluíram em entidades separadas. O conteúdo da página é armazenado no DOM e pode ser acessado e manipulado via JavaScript, portanto nós podemos escrever esta equação aproximativa:
</p><p>API(web ou página XML) = DOM + JS(linguagem de scripting)
</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="eval"># 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>
<h3 name="How_Do_I_Access_the_DOM.3F">How Do I Access the DOM?</h3>
<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 in-line 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="pt/DOM/document">document</a></code> or <code><a href="pt/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="pt/DOM/window.alert">alert()</a></code> function from the <code><a href="pt/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="eval">&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="eval">&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
   heading = document.createElement("h1");
   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>
<h3 name="Important_Data_Types">Important Data Types</h3>
<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 border="1" cellpadding="5" cellspacing="0">
  <tbody><tr>
    <td><code>document</code></td>
    <td>When a member returns an object of type <code>document</code> (e.g., the <b>ownerDocument</b> 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="pt/Gecko_DOM_Reference/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 <code>document.createElement()</code> 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 <code>document.getElementsByTagName()</code>. Items in a <code>nodeList</code> are accessed by index in either of two ways: 
<ul><li> list.item(1)
</li><li> list{{mediawiki.external(1)}}
</li></ul>
<p>These two are equivalent. In the first, <b>item()</b> 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.
</p>
</td>
  </tr>
  <tr>
    <td><code>attribute</code></td>
    <td>When an <code>attribute</code> is returned by a member (e.g., by the <b>createAttribute()</b> 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>
<h3 name="DOM_Interfaces">DOM Interfaces</h3>
<p>This guide is about the objects and the actual <i>things</i> you can use to manipulate the DOM hierarchy. It's often a matter of indifference that the object representing the <code>HTML FORM</code> element gets its <b>name</b> property from the <code>HTMLFormElement</code> interface but its <b>className</b> property from the <code>HTMLElement</code> interface proper. In both cases, the property you want is simply in the 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>
<h4 name="Interfaces_and_Objects">Interfaces and Objects</h4>
<p>Many objects borrow from several different interfaces. The table object, for example, implements a specialized <a href="pt/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="pt/Gecko_DOM_Reference/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 a web page or an 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>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>
<h4 name="Core_Interfaces_in_the_DOM">Core Interfaces in the DOM</h4>
<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="pt/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="pt/DOM/document.getElementById">document.getElementById</a>(id)</code>
</li><li> <code>element.<a href="pt/DOM/element.getElementsByTagName">getElementsByTagName</a>(name)</code>
</li><li> <code><a href="pt/DOM/document.createElement">document.createElement</a>(name)</code>
</li><li> <code>parentNode.<a href="pt/DOM/element.appendChild">appendChild</a>(node)</code>
</li><li> <code>element.<a href="pt/DOM/element.innerHTML">innerHTML</a></code>
</li><li> <code>element.<a href="pt/DOM/element.style">style</a>.left</code>
</li><li> <code>element.<a href="pt/DOM/element.setAttribute">setAttribute</a></code>
</li><li> <code>element.<a href="pt/DOM/element.getAttribute">element.getAttribute</a></code>
</li><li> <code>element.<a href="pt/DOM/element.addEventListener">addEventListener</a></code>
</li><li> <code><a href="pt/DOM/window.content">window.content</a></code>
</li><li> <code><a href="pt/DOM/window.onload">window.onload</a></code>
</li><li> <code><a href="pt/DOM/window.dump">window.dump</a></code>
</li><li> <code><a href="pt/DOM/window.scrollTo">window.scrollTo</a></code>
</li></ul>
<h3 name="Testing_the_DOM_API">Testing the DOM API</h3>
<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 &lt;script&gt; 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 &lt;script&gt; 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>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;DOM Tests&lt;/title&gt;
&lt;script type="application/x-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; color&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;/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;/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><p><img alt="Image:DOM_Ref_Introduction_to_the_DOM.gif" src="File:pt/Media_Gallery/DOM_Ref_Introduction_to_the_DOM.gif"><br>
Figure 0.1 Sample DOM Test Page
</p><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>{{ wiki.languages( { "en": "en/Gecko_DOM_Reference/Introduction", "fr": "fr/R\u00e9f\u00e9rence_du_DOM_Gecko/Introduction", "ja": "ja/Gecko_DOM_Reference/Introduction", "pl": "pl/Dokumentacja_Gecko_DOM/Wprowadzenie", "zh-cn": "cn/Gecko_DOM_\u53c2\u8003/\u5165\u95e8", "es": "es/Referencia_DOM_de_Gecko/Introducci\u00f3n" } ) }}
Reverter para esta revisão