Creating a Cross-Browser (DOM) Expandable Tree

jsTree Methods

The first method of the jsTree class is fairly obvious: we need to be able to create
the root of the tree. So, we will make the createRoot() method, which will take the
same parameters as the addChild() method for the jsTreeNode class. The
createRoot() method does the exact same things as the addChild() method, with
the exception that it assigns the created node to the tree's root property:

Next, we want a way to initiate the creation of the HTML for the tree. We wrote a method for
the jsTreeNode class called addToDOM(). For the jsTree, we
will make a method called buildDOM(). The only step of this method is to call the
addToDOM() method on the tree's root and pass in the HTML document body as
the parent element:

The last method of the jsTree class is the one that will expand or collapse any
node in the tree. This is important so that the plus/minus image will always have the same URL to
cause either an expand or a collapse, depending on the state of the node. We will call this method
toggleExpand(), which will take one parameter: the unique ID of the jsTreeNode
to expand or collapse (bet you thought we'd never use that ID).

The first step in this method is to get the node in question by using the global nodes collection
to locate it. Once we do, we can check to see if it should be expanded or collapsed, and then take the
appropriate action. The code for this method is:

Wrapping Up

Now that we have written all of our code, it is time to make a nice example to show it off.
The first step, of course, is to create the root of the tree using the createRoot()
method. After that, you can add nodes to your heart's delight. For example, I decided to use this
code to make a tree that is exactly what I see when I look at Windows Explorer on my computer.
Take a look for yourself (opens in a new window). You can
view the source for a great example.

And remember, we didn't use any browser detection at all. Test it in IE 5.0+ and Netscape 6.1+, bet
you can't tell the difference!

About the Author

Nicholas C. Zakas is a user interface designer for web applications at
MatrixOne, Inc. in Massachusetts. Nicholas works primarily as a client-side
developer using JavaScript, DHTML, XML and XSLT. He can be reached via
e-mail at nicholas@nczonline.net or at
his Web site, http://www.nczonline.net.