July 14, 2001 - Accessing the Document's Root | WebReference

July 14, 2001 - Accessing the Document's Root

Yehuda Shiran July 14, 2001
Accessing the Document's Root
Tips: July 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

The DOM models an HTML document as a tree. The root of the tree is the document object. The node representing the root is document.documentElement. You can learn how to descend from the root to its children and back, from the columns listed at the bottom of this tip. A relationship that was not supported before Internet Explorer 6 (and therefore not covered by the columns below) is the document context of a node. Each tag you define in an HTML file (each tag is modeled by a node on the DOM tree), belongs to a certain document object. This ownership relationship is given by the ownerDocument property. If we model the whole document by a single DOM tree, the ownerDocument property is a direct pointer from any node on the DOM tree to the root of the tree. The following expression should return the root of the DOM tree:


Let's print the node name (tag name), so it's easier to recognize which node it is. You should get HTML. For printing the root's properties, always go the root node by using the documentElement property. The printing above is actually done via:


Now, let's go deeper in the tree, to the document's first child (HEAD):


And then let's go directly back to the root of the DOM tree:


As previously shown, let's print the node name of the root. Again, we go to the root node by the documentElement property:


You should get HTML.

The code in this tip can be viewed only by Internet Explorer 6 and up, as well as Netscape 6 and up.

Learn more about the DOM in Columns 40, The DOM, Part I: Analysis, through Column 47, A DOM-Based Snakes Game, Part II.