Pages

Navigating Through the DOM

Since , DOM model is based on tree structure every element has a parent node (except document node) and every parent node has a child node .

parentNode

Consider this HTML :

         <p>
           <a id="techblog" href="http://netdweb.blogspot.com/">NetdWeb</a>
         </p>

 Here , <p> element is the parent element of the <a> element . To acces <p> from <a>  :


           var IDattrib= document.getElementById("techblog");
           var paragraph = techblog.parentNode;

 IDattrib variable refers to <a> element and paragraph variable to the parent node <p> .


 Since in a tree each child has only one parent but each parent can have many children  childNodes property references to all children of a parent . Suppose , if techblog is the Id of the parent node and you want to reference the fourth child of this parent :


                       var parentID = document.getElementById("techblog");
                       var childname = techblog.childNodes[3];


Keywords  firstChild and lastChild can be used to access the first and the last child of the parent . e.g


                        var first = techblog.firstChild;
 

                        var last = techblog.lastChild;



Nodes at the same level in the tree are referred to as siblings .  previousSibling and nextSibling are two keywords used to reference previous and next siblings . e.g.


                                                var x = y.nextSibling;

This stores next sibling to y in x .

                                               var a= b.previousSibling;

This stores previous sibling to b in a .