I created a version for several levels of the hierarchy as an answer to another question .
jQuery for your table will be:
var treeTable = { parentClassPrefix : '', collapsedClass : 'collapsed', init : function(parentClassPrefix) { this.parentClassPrefix = parentClassPrefix; $('table').on('click', 'tr', function () { treeTable.toggleRowChildren($(this)); }); }, toggleRowChildren : function(parentRow) { var childClass = this.parentClassPrefix+parentRow.attr('id'); var childrenRows = $('tr', parentRow.parent()).filter('.'+childClass); childrenRows.toggle(); childrenRows.each(function(){ if (!$(this).hasClass(treeTable.collapsedClass)) { treeTable.toggleRowChildren($(this)); } }); parentRow.toggleClass(this.collapsedClass); } }; treeTable.init('parent_');
See JSFiddle for work.
Optimization
I have a slightly different table structure that includes an indication of the parents as well as the children so that the search can be more efficient.
Then I also made a hierarchical row of the jQuery table, switching the Gist , and converting it to objectified javascript with optimization. Optimizations come from http://24ways.org/2011/your-jquery-now-with-less-suck/ .
In particular:
Delegation of events in a table, not in rows.
$('table').on('click', 'tr.'+treeTable.parentClass, function () { treeTable.toggleRowChildren($(this)); });
Cache for choosing children.
Use a faster element selector followed by a slower filter on .childClass
var childrenRows = $('tr', parentRow.parent()).filter('.'+childClass);
icc97
source share