Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Understanding DOM Structure

In Hour 9, "Working with the Document Object Model," you learned about how some of the most important DOM objects are organized: The window object contains the document object, and so on. While these objects were the only ones available in older browsers, the new DOM adds objects under the document object for every element of a page.

To better understand this concept, let's look at the simple HTML document in Listing 19.1. This document has the usual <head> and <body> sections, a heading, and a single paragraph of text.

Example 19.1. A simple HTML document

<html>
<head>
<title>A simple HTML Document</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph</p>
</body>
</html>

Like all HTML documents, this one is composed of various containers and their contents. The <html> tags form a container that includes the entire document, the <body> tags contain the body of the page, and so on.

In the DOM, each container within the page and its contents are represented by an object. The objects are organized into a tree-like structure, with the document object itself at the root of the tree, and individual elements such as the heading and paragraph of text at the leaves of the tree. Figure 19.1 shows a diagram of these relationships.

19fig01.gif

Figure 19.1 How the DOM represents an HTML document.

In the following sections, you will examine the structure of the DOM more closely.

Nodes

Each container or element in the document is called a node in the DOM. In the example in Figure 19.1, each of the objects in boxes is a node, and the lines represent the relationships between the nodes.

You will often need to refer to individual nodes in scripts. You can do this by assigning an ID, or by navigating the tree using the relationships between the nodes.

Parents and Children

As you learned earlier in this book, each JavaScript object can have a parent—an object that contains it—and can also have children—objects that it contains. The DOM uses the same terminology.

In Figure 19.1, the document object is the parent object for the remaining objects, and does not have a parent itself. The html object is the parent of the head and body objects, and the h1 and p objects are children of the body object.

Text nodes work a bit differently. The actual text in the paragraph is a node in itself, and is a child of the p object. Similarly, the text within the <h1> tags is a child of the h1 object.

Siblings

The DOM also uses another term for organization of objects: siblings. As you might expect, this refers to objects that have the same parent—in other words, objects at the same level in the DOM object tree.

In Figure 19.1, the h1 and p objects are siblings: both are children of the body object. Similarly, the head and body objects are siblings under the html object.

Share ThisShare This

Informit Network