JavaScript: the firstChild and lastChild DOM properties

In this post I'm going to show you how to implement a basic DOM navigation system using the JavaScript's implementation of the DOM specifications. More specifically, we're going to use the firstChild and lastChild properties of a DOM node to navigate a basic DOM structure. Further, our code will take into account the problem of ghost nodes, that is, line breaks or white space considered as nodes by most browsers.

We start everything out by defining a really simple structure to work with:

<ul id="test">

<li>A</li>
<li>B</li>
<li>C</li>

</ul>

As you can see, this structure has two blank spaces, one at the beginning and the other at the end of the structure itself. So we're going to take all this into account, like so:

window.onload = function() {


   var DOMNav = {
   
   
      start: document.getElementById('test'),
      
      first: function() {
      
         var element;
      
         if(this.start.hasChildNodes()) {
         
         
            if(this.start.firstChild.nodeType == 1) {
            
            
                element = this.start.firstChild;
            
            
            } else {
            
            
                element = this.start.firstChild.nextSibling;
            
            }
         
         
         }
         
         return element;
      
      
      },
      
      last: function() {
      
      
          var element;
          
          if(this.start.hasChildNodes()) {
          
          
              if(this.start.lastChild.nodeType == 1) {
              
              
                  element = this.start.lastChild;
              
              
              } else {
              
                  element = this.start.lastChild.previousSibling;
              
              }
          
          
          }
          
          return element;
      
      
      
      }
   
   
   };
   

var first = DOMNav.first();
var last = DOMNav.last();

alert(first.firstChild.nodeValue);
alert(last.firstChild.nodeValue);

};

When using these properties, we first make sure that the current node is an element node. If so, we return that element. Otherwise, we move to the next or previous node to get the correct value. You can see a demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.