Visit Mozilla.org

Code snippets:Tree

From MDC

Contents

[edit] Expanding/Collapsing all tree nodes

To expand all tree nodes:

 var treeView = tree.treeBoxObject.view;
 for (var i = 0; i < treeView.rowCount; i++) {
   if (treeView.isContainer(i) && !treeView.isContainerOpen(i))
     treeView.toggleOpenState(i);
 }

To collapse all tree nodes just change the condition:

 var treeView = tree.treeBoxObject.view;
 for (var i = 0; i < treeView.rowCount; i++) {
   if (treeView.isContainer(i) && treeView.isContainerOpen(i))
     treeView.toggleOpenState(i);
 }

[edit] Getting the text from the selected row

Assuming the given <tree>:

 <tree id="my-tree" seltype="single" onselect="onTreeSelected()">

Use the following JavaScript:

 function onTreeSelected(){
   var tree = document.getElementById("my-tree");
   var cellIndex = 0;
   var cellText = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(cellIndex));
   alert(cellText);
 }

[edit] Getting the tree item from the selected row

Assuming <tree id="my-tree">, You can use the following to get the tree item:

 var sel = fcTree.tree.currentIndex; //returns -1 if nothing is selected
 var treeItem = document.getElementById("my-tree").view.getItemAtIndex(sel);

[edit] Getting the cell from a mouse click

Your first choice is likely to try <treecell onclick="yourfunc();"/> or something similar. But this will not work. You can't add event handlers to <treecell>. Instead, you can add the event handler to the <tree> element. You can then use the event and some utility methods to find the <treecell>. For example, assuming the given <tree>:

 <tree id="my-tree" onclick="onTreeClicked(event)">

Use the following JavaScript:

function onTreeClicked(event){
  var tree = document.getElementById("my-tree");
  var tbo = tree.treeBoxObject;

  // get the row, col and child element at the point
  var row = { }, col = { }, child = { };
  tbo.getCellAt(event.clientX, event.clientY, row, col, child);

  var cellText = tree.view.getCellText(row.value, col.value);
  alert(cellText);
}

[edit] Other resources