Online
 
Sunday, 23 November 2008
 
 

JavaScript - Traversing a document tree | Print |  E-Mail
 

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)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Jumbo Coklat
 
Top! Top!