How to recursively traverse a DOM element in JavaScript

Suppose you want to traverse all the child nodes of a DOM element in order to do something with them, such as disabling them for example.  Here’s one way to do it.


In this example, the function that is responsible to traverse the DOM element’s child nodes and disable them is the recursive function EnableDisableDOMElement.  You have no choice but to use a while loop because you don’t know exactly the depth of each child nodes of every DOM element. 

You can use this code by calling the DisableDOMElementTree function (feel free to name it according to your intention) and pass it a DOM element as a parameter. For instance, in the onload event of the body element, you can call DisableDOMElementTree and pass it a valid DOM element which is the root of the elements tree. You can use document.getElementById with the name of a DOM element as a parameter to the function.

Hope it helps!

This post has been viewed: 1783 times. kick it on DotNetKicks.com

 

Similar posts you might be interested in reading:

2 Comments

  1. C-J Berg:

    IMHO you should always use jQuery instead (or at least some other JS library). It is compatible with *all* major browsers, it often runs faster than your own code would (it has lots of battle-tried optimizations), and most importantly: it is a joy to use!

    Jeff Atwood recently wrote about the neccessity of using a JavaScript library:
    http://www.codinghorror.com/blog/archives/001163.html

  2. Brian Di Croce:

    Thanks for the input! I heard of JQuery, but I thought it was a derivative of Java…you just taught me something new C-J.

Leave a comment

Powered by WP Hashcash