Recursive iteration through the HTML DOM

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)
		for(x=0;x<node.childNodes.length;x++) { var childNode = node.childNodes[x]; task(childNode); 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.

Leave a Reply

Your email address will not be published. Required fields are marked *