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!
Similar posts you might be interested in reading:
- Null Coalescing Operator
- Inserting and Retrieving An Image In SQL Server 2005
- Getting Familiar With Your Basic .NET Delegates
- Calling Native Win32 Functions in .NET? PInvoke.NET to the Rescue!
- Three Index Cards To Easily Remember The Essence Of Test-Driven Development
- Virtual PC Console window doesn’t show up when launching
- God’s Pharmacy Is Simply Amazing!






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:
August 21, 2008, 3:21 amhttp://www.codinghorror.com/blog/archives/001163.html
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.
August 21, 2008, 8:45 am