RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Build an XML-based Tree Control with JavaScript : Page 6

Tree controls provide a hierarchical view of data and XML provides a way to structure data hierarchically, so viewing XML data as a tree structure is a natural fit. But browsers don't provide a tree control. Instead, use this mix of XML, XSLT, JavaScript, and CSS to produce an extensible HTML tree control.

Embed the Tree in an HTML Document
In most cases, the tree control will be a component in another Web page. The transformation above creates the tree for viewing in a browser but, usually, you'll want to surround the tree with other content.

Both IE and N7 use the same mechanism for embedding external content—the <iframe> element. Here's a simple method for embedding the tree in another page:

   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
       <title>Embedded XML Tree Control</title>
   <style type="text/css">
      border-right:1px black solid;
      border-top: none;
      border-bottom: none;
      position: absolute;
      width: 150;
      left: 160;
      font-family: sans-serif;
      color: navy;
   <script type="text/javascript">
   function setHeight(){
      var availableHeight = 0;
         availableHeight = document.body.clientHeight;
         availableHeight = innerHeight;
      var tree = document.getElementById('tree').style;
      tree.height = availableHeight-20;
   <body onload="setHeight()">
      <iframe id="tree" src="tree.xml"></iframe> 
      <div id="content">
        <h2>Page Content Here</h2>
In my opinion, Mozilla renders this HTML file correctly but IE doesn't. IE insists on displaying a scrollbar for the <iframe>—even when it isn't necessary.

I've barely scratched the surface of XSLT and XPath. There are tomes of information on the subject. I advise you to inform yourself through whatever means available to you on XML and its accompanying technologies.

The good news is that the solution I've implemented here will work for any XML document that adheres to the tree DTD. Because the implementation breaks the tree into smaller, more manageable pieces, the tree control is both maintainable and extensible. The solution also allows you to concentrate on the content of the tree—freeing you from the underlying complexity. Finally, the solution works in both of the major browsers currently available.

Tom Duffy , DevX's JavaScript Pro, is an Associate Professor at Norwalk Community College, Norwalk, CT where he teaches Web Development and Java. Tom is also the Manager of the NCC Ventures Lab, the college's in-house Web design studio. You can reach him via e-mail .
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date