JavaScript: walking the DOM without jQuery

Sometimes it's useful to rediscover some basic DOM methods and properties in order to become more independent from a JavaScript framework like jQuery. The only problem with jQuery is that it makes the life too easy for us, in the sense that we tend to forget how to achieve certain results without it. Suppose, for example, that we have a DOM structure like the following:

<ul id="list">
 
 <li>Item</li>
 
 <li>Item</li>
 
 <li><span>Item</span></li>
 
</ul>

Now we want to collect some information about this structure. To accomplish this task, we can write the following function:

function walkTheDOM(reference) {
  
  
  var tree = document.createElement('ul');
  var body = document.body;
  
  
  var html = '';
  
  var element = document.getElementById(reference);
  
  var children = element.childNodes;
  
  for(var i=0; i<children.length; i++) {
   
   if(children[i].nodeType == 1) {
    
    var child = children[i].firstChild;
    var childText = child.nodeValue;
    
    if(child.nodeType == 1) {
     
     
     html += '<li><ul><li>' + child.firstChild.nodeValue + '</li></ul></li>';
     
     
    } else {
     
     html += '<li>' + childText + '</li>';
     
    }
    
    
   }
   
   
  }
  
  tree.innerHTML = html;
  body.appendChild(tree);
  
  
}
 
walkTheDOM('list');

As you can see, to extract the information we need we use the childNodes collection together with a check on the type of child node contained within each node. Only if the child is an element or a text node we collect it, otherwise the node is ignored. You can see the result below.

Leave a Reply

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