Traversing the DOM in JavaScript

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.

<html>

    <head>

        <script>

            alert("Body from HEAD: "+document.body) // null

        </script>

    </head>

    <body>

        <div>ABHIJEET</div>

 

        <script>

            // for different browsers ,output is different text, 

            // because of different implementations of toString 

 

            alert("Body from inside body: " + document.body) 

        </script>

    </body>

</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.

<html>

  <body>

    <div>Welcome:</div>

    <ul>

      <li>Abhijeet</li>

      <li>Bittoo</li>

    </ul>

<script>   

      function abhi() {

        var childNodes = document.body.childNodes

 

        for(var i=0; i<childNodes.length; i++) {

            alert(childNodes[i])

        }

      }

    </script>

 

    <button onclick="abhi()" style="width:100px">Come on!</button>

 

  </body>

</html>




Children:

Sometimes we need to browse only element nodes, skipping text nodes. For this we use children.

It contains all element nodes.

<html>

  <body>

    <div>Welcome:</div>

    <ul>

      <li>Abhijeet</li>

      <li>Bittoo</li>

    </ul>

 

    <script>   

      function abhi() {

        var children = document.body.children

 

        for(var i=0; i<children.length; i++) {

            alert(children[i])

        }

      }

    </script>

 

    <button onclick="abhi()" style="width:100px">Come on!</button>

 

  </body>

</html>

 

Up Next
    Ebook Download
    View all
    Learn
    View all