| JavaScript - Traversing a document tree | | Print | |
Traversing a document tree
The W3C DOM represents every document as a tree. The nodes of this tree represent the HTML tags, the strings of text, and the HTML comments that comprise the document. Each node of the tree is represented by a JavaScript object, and each has properties that allow you to traverse the tree, as illustrated by the following code fragment:
// Look up a node in the document
var n = document.getElementById("mynode");
var p = n.parentNode; // The containing tag
var c0 = n.firstChild; // First child of n
var c1 = c0.nextSibling; // 2nd child of n
var c2 = n.childNodes[2]; // 3rd child of n
var last = n.lastChild; // last child of n
See Node in the reference section for further details.
The Document object itself is a kind of node, and supports these same properties. The documentElement property of the Document object refers to the single <html> tag element at the root of all HTML documents, and the body property refers to the <body> tag.
This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
| Users' Comments (0) |
|
No comment posted






