Javascript – Traversing the HTML DOM recursively

This post will give idea about HTML DOM Objects and way we can use its methods and attributes to navigate or traverse through it.

Introduction:
How to traverse the complete HTML BODY covering each HTML element recursively and forming a tree You need to be aware of very basic Javscript DOM methods. W3schools is the wonderful resource to learn this basics. Go through all the functions but what we need for this exercise is getElementById() and getElementsByTagName()

Eg: HTML

<html>
  <head>
    <title>
      Javascript - HTML Tree Parser
    </title>
  </head>
  <body>
    <div id="header">
      <h1>Javascript - HTML Tree Parser</h1>
    </div>
    <ul id="nav">
      <li><a href="one.html">one</a></li>
      <li><a href="two.html">two</a></li>
    </ul>
    <div id="footer">
    </div>
  </body>
</html>

Step I:
We are going to write a javascript function – lets call it htmlTree

<script type="text/javascript">
   function htmlTree(){}
</script>

Step II:
We will need to first get the body element, we can do it with the help of getElementsByTagName(‘body’), which will return you the body tag. But since the function itself is plural it will always return you an array even if it has only one single element. Since body is the present only once we will refer to the 0th element of an array.

<script type="text/javascript">
  function htmlTree(){
    var body = document.getElementsByTagName('body')[0];
  }
</script>

Step III:
Now we will check if the body tag has any children – we can do that by using hasChildNodes() method, if yes then we will first refer to the first child, we can do that with the attribute “firstChild”. Also we can get the name of the tag with an attribute “tagName”. After reading the first child we will go to the next child, with use of an attribute “nextSibling”

<script type="text/javascript">
  function htmlTree(){
    var body = document.getElementsByTagName('body')[0];
    if (body.hasChildNodes()) {
      var child = body.firstChild;
      alert(child.tagName); // as per the above HTML example it will alert "div"
      var next = child.nextSibling;
      alert(next.tagName); // as per the above HTML example it will alert "ul"
    }
  }
</script>

But this wont meet our purpose, we dont know the length of the tree and we also dont know how deep each branch is going to be, so we will make this function recursive to perform these similar step for eavery branch till it reaches it leaves.

Step IV:
We will print the name of the tag identified and check if it has children if yes then we will recursively call the function again which will print its name and check if it has child – it will happen till it reaches element with no child

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    alert(obj.tagName);
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      htmlTree(child);
    }
  }
</script>

When you execute this, you get first alert as BODY but very next alert as undefined – where in it should have been DIV. This is because between BODY and the DIV tag there is the white space which is considered to be an empty text – well we need to avoid such occurrences

Step V:
Go through nodeType on W3schools. Since here we are looking for an HTML elements, we will check for nodeType = 1. If it is 1 then we will recursively call the function if not we will move onto its sibling

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    alert(obj.tagName);
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      while(child){
        if (child.nodeType === 1) {
          htmlTree(child);
        }
        child = child.nextSibling;
      }
    }
  }
</script>

Step VI:
These alerts are quiet annoying, so lets make some subtle changes so that this function returns us complete tree. I personally like “ul li ul li” to represent a tree. Here is the modified function

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    var str = "<ul><li>" + obj.tagName;
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      while (child) {
        if (child.nodeType === 1) {
          str += htmlTree(child)
        }
        child = child.nextSibling;
      }
    }
    str += "</li></ul>";
    return str;
  }
  document.write(htmlTree());
</script>

Step VII:
Since at the very beginning we were talking about just HTML elements, we will get rid of all the javascript inside HTML. We can achieve that by simply adding a simple check in the condition where we check the nodeType.

// Change
if (child.nodeType === 1)
// to
if (child.nodeType === 1 && child.nodeName != 'SCRIPT')

Demo:
Javascript – HTML Tree Parser

dovalidate-js – Javascript Form Validation Library

I have been working on the javascript library to meet my everyday basic needs. dovalidate-js is the result of it.

Client side validation of form submission is very crucial and important. This is an attempt to create a dynamic library which will do the basic validation with some amount of configuration available to the user using it as per the requirement.

The main goal behind building the validator is to avoid playing with html form and let javascript do the validation and css highlight it.

So that it can be applicable to the already created form without touching it but by just configuring it through javascript and css.

Steps to use it:
Step 1:
Include a javscript file

<script type="text/javascript" src="scripts/dovalidate-0.1.js"></script>

Step 2:
Create the instance of validator

var dovalidate = new SWAPJS.doValidate();

Step 3:
Call the validator init function with appropriate parameters.
The parameters foremost consists of the id of the HTML form which you want to validate. Second the set of ids of the elements which you want to validate with the type of validation you want to have on it.

dovalidate.init('form_id', {
   name: ['empty'], // Comment 1
   email: ['empty', 'email'], // Comment 2
   webpage: ['url'] // Comment 3
});

Comment 1: ‘name’ is the id of an element. ‘empty’ is the type of validation
‘empty’ is in other words required field, if ‘name’ field is empty form would not submit
Comment 2: ‘email’ is the id of an element. ‘empty’ and ‘email’ are the type of validations
if more than one type validation specified. then both the validation should pass so that form can be submitted
Comment 3: ‘webpage’ is the id of an element. ‘url’ is the type of validation
no ‘empty’ specified means, the field is not mandatory, but if it has some content it has to be of the specified type or else it wont submit

Example:

<script type="text/javascript" src="scripts/dovalidate-0.1.js"></script>
<script type="text/javascript">
	var dovalidate = new SWAPJS.doValidate();
	dovalidate.init('form1', {
		name: ['empty'],
		email: ['empty', 'email'],
		webpage: ['url'],
		comment: ['empty'],
		phone: ['digits']
	});
</script>

dovalidate-js:
dovalidate-js demo
dovalidate-js download

Wondering n’ Finding the reason

I saw her walking down the street,
She didn’t let our eyes to meet.
Something was going in her mind,
My eyes were trying to find.

But she didn’t let it happen,
I don’t know why was she feeling shy.
We didn’t have any relation,
But my heart gave out a cry.

Hey girl, why you let this happen,
Why the feeling in your heart is denied.
Why don’t you let our love to sharpen,
Baby, I’m one of the kind.