Traversing the DOM in JavaScript

Introduction

 
To traverse the DOM, the access always starts from the document. 
 
The root: documentElement and body
 
The root of the DOM is always document.documentElement.
 
This special property will provide access to the topmost HTML tag.
 
Another starting point can be the document.body, which represents the BODY tag.
 
 
Both entry points are valid. But document.body can be null.
 
For example, we access document.body from an inline script in the HEAD, prepare to see null instead. That’s natural, because there is no BODY yet.
  1. <html>  
  2.     <head>  
  3.         <script>  
  4.             alert("Body from HEAD: "+document.body) // null  
  5.         </script>  
  6.     </head>  
  7.     <body>  
  8.         <div>ABHIJEET</div>  
  9.    
  10.         <script>  
  11.             // for different browsers ,output is different text,   
  12.             // because of different implementations of toString   
  13.    
  14.             alert("Body from inside body: " + document.body)   
  15.         </script>  
  16.     </body>  
  17. </html> 
On the contrary, document.documentElement is always available.
 
document.body can’t be undefined.
 
In the world of the DOM, an “element not found” or “no such element” is always null.
 
Child elements
 
childNodes
 
An element keeps references to children in childNodes array-like property.
  1. <html>  
  2.   <body>  
  3.     <div>Welcome:</div>  
  4.     <ul>  
  5.       <li>Abhijeet</li>  
  6.       <li>Bittoo</li>  
  7.     </ul>  
  8. <script>     
  9.       function abhi() {  
  10.         var childNodes = document.body.childNodes  
  11.    
  12.         for(var i=0; i<childNodes.length; i++) {  
  13.             alert(childNodes[i])  
  14.         }  
  15.       }  
  16.     </script>  
  17.    
  18.     <button onclick="abhi()" style="width:100px">Come on!</button>  
  19.    
  20.   </body>  
  21. </html> 
 
 
Children
 
Sometimes we need to browse only element nodes, skipping text nodes. For this we use children.
 
It contains all element nodes.
  1. <html>  
  2.   <body>  
  3.     <div>Welcome:</div>  
  4.     <ul>  
  5.       <li>Abhijeet</li>  
  6.       <li>Bittoo</li>  
  7.     </ul>  
  8.    
  9.     <script>     
  10.       function abhi() {  
  11.         var children = document.body.children  
  12.    
  13.         for(var i=0; i<children.length; i++) {  
  14.             alert(children[i])  
  15.         }  
  16.       }  
  17.     </script>  
  18.    
  19.     <button onclick="abhi()" style="width:100px">Come on!</button>  
  20.    
  21.   </body>  
  22. </html>