Nodes have a hierarchical relationship to each other. Take this HTML snippet:
The snippet contains two nodes: one element node for the
<p> node contains the text node, their relationship becomes parent (
<p>) and child (text).
In this hierarchical way, all nodes form a document tree. This tree starts at the document node itself and continues to branch out until it has reached all text nodes that reside at the lowest level of the tree.
Take this simple HTML page:
The Level 1 DOM sees it as the following node tree:
The node type determines what you're allowed to do with a node. For instance, text nodes cannot contain other nodes, so, unlike element nodes, they have no child nodes. On the other hand, they have a few properties for reading out the text, which is something element nodes can't do (and don't need to do).
All these nodes have relationships to each other, and the DOM uses terminology borrowed from family trees to describe these relationships. Every node except for the document has a parent node. For instance, the parent node of the
<body> element node is the
<html> element node, and the parent node of the 'Hello world!' text node is the
<h1> element node.
Most element nodes have child nodes. For instance, the
<head> node has one child node: the
<title> node. In turn, the
<title> node has a text node as its child node.
Some nodes are siblings because they share a parent. For instance, the
<p> nodes are siblings because they're both child nodes of the
Nodes can have descendants and ancestors. Descendants are all the nodes that are children of a node, or children of those children, etc. For instance, all text nodes are descendants of the
<html> node, while the second and third text nodes are descendants of the
Ancestors are nodes that are parents of a node, or parents of this parent, etc. All text nodes have the
<html> node as an ancestor, while the second and third text nodes have the
<body> element as an ancestor.
You can run up and down this family tree in order to find nodes. For instance, the
<h1> node contains a property parentNode that refers to its parent: the
You can also directly find an element with a certain ID (
getElementById()) or all elements with a certain tag name (
Changing the tree
The W3C DOM allows you to change the node tree of a document. The following snippet changes the document tree:
Figure 8.2: The DOM tree as rendered by the browser before (above) and after (below) the script has run.
<p> nodes now trade places, both in the DOM tree and in the browser window. This shows the great power of the W3C DOM: any change to the tree is immediately rendered by the browser and becomes visible to your users.
The W3C DOM also allows you to create new elements and insert them in the document tree. This means that you can add anything to the document: status texts, new data obtained from an
XMLHttpRequest script (see Chapter 10), or anything else that strikes your fancy.