NOTE: Please click here for a flash/actionscript version of this technique.

Sometimes it is useful to be able to iterate through every element in a HTML document–or all of the children of a specific HTML node–and either perform an operation on each element or access a property of each element. We need to use recursion in order to do this because child elements of a html node may themselves contain more child nodes. WARNING! It can become quite processor intensive using recursion to iterate through a large number of elements. Below is a javascript example which puts this technique into practice. All source files can be downloaded here.

First we define a class which will be responsible for iterating through the document object model (DOM) and calling a method on each child node. The method will be supplied as an argument and must define a html node as one of its own arguments. This allows us to define a method we would like to apply to all of our elements externally and independent of the class.

function HTMLNodeIterator()
	//task:function,node:HTML Node
	this.iterate = function iterate(task,node)
			var childNode = node.childNodes[x];
			if( childNode.childNodes.length > 0 )

Next we will use the class to draw red borders around our elements, this method will be applied to every element in the DOM, however borders will only be drawn on div elements.

var bodyElement = document.getElementsByTagName("body")[0];
var htmlNodeIterator = new HTMLNodeIterator();
function drawBorders(node)
	if(node.nodeName == "DIV")
	{ = "solid 1px #ff0000";

We could use the iterator class for something more useful such as providing information about each element or counting the number of certain elements at run time. ie: for memory profiling. Please click here to download the full source and an example.

The problem with recursion is it’s very easy to create an infinite loop.

The problem with recursion is it’s very easy to create an infinite loop……..

2 Responses to “Recursive iteration through the HTML DOM”

  1. Vijaya Anand says:

    Hi Ben,

    That’s a nice job. Needs a little correction I think. In the for loop you have to include a VAR for initializing variable x to avoid making it as a global variable.

    for(VAR x=0;x 0 )

    Vijaya Anand .M

  2. admin says:

    Thanks Vijaya. I didn’t know that.