Section 27.3. The DOM


27.3. The DOM

Perhaps the easiest way to think of the DOM is to think of the document tree . Let's take the following XHTML document as an example:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>   <title>Sample XHTML</title>   <meta http-equiv="content-type"     content="text/html; charset=iso-8859-1" />   <meta http-equiv="Content-Language" content="en-us" /> </head> <body>   <h1>This is a heading, level 1</h1>   <p>This is a paragraph of text with a     <a href="/path/to/another/page.html">link</a>.</p>   <ul>     <li>This is a list item</li>     <li>This is another</li>     <li>And another</li>   </ul> </body> </html> 

This is a pretty basic web page, making use of a few different elements. If we were to visualize this as a document tree , it would look something like Figure 27-1.

Figure 27-1. A sample document tree


A document tree like this is roughly akin to a very high level view of the DOM's node tree.

Essentially, the DOM is a collection of nodes. These nodes usually take one of three forms:

  • Element nodes

  • Attribute nodes

  • Text nodes

These nodes are arranged in a hierarchy that we sometimes refer to using a familial model. In (X)HTML, the hierarchy begins with the html element, which is the root element, meaning it has no ancestors. In the above example, html has two child nodes (head and body). The head element has three child nodes of its own (a title and two meta elements), as does body (h1, p, and ul). The relationship goes in the other direction as well, with each child having a parent node. Similarly, elements that share a parent are referred to as sibling nodes.

If you are familiar with using selectors in Cascading Style Sheets (CSS), referring to element nodes in a familial structure should make perfect sense. There are, however, a few differences between the document tree used in CSS and node tree of the DOM, which bear further discussion.

Figure 27-1 is a very high-level view of the DOM because it is only showing the element nodes. Using the DOM, we can dig deeper. Figure 27-2 examines the paragraph element of the example above.

Figure 27-2. An examination of the p element in Figure 27-1


As you can see, the paragraph contains three child nodes of its own: two text nodes (the rounded white boxes) and an anchor element (a). The a, itself, has a child node that is a text node and it also has an attribute node: its href (the gray rounded box).

Using the DOM, we can leverage these relationships to do all sorts of things to our documents.




Web Design in a Nutshell
Web Design in a Nutshell: A Desktop Quick Reference (In a Nutshell (OReilly))
ISBN: 0596009879
EAN: 2147483647
Year: 2006
Pages: 325

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net