I am looking for an efficient way to expand/collapse hierarchical table rows using jQuery. The problem is, that the expand and collapse functionality differs.
I've created a version for multiple levels of hierarchy as an answer to another question.
The jQuery for your table would 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 this JSFiddle for it working.
I have a slightly different table structure, which involves specifying parents as well as children so that the searching can be more efficient.
I've then also made a jQuery hierarchical table row toggling Gist from it and converted it into objectified javascript with optimisations. The optimisations come from http://24ways.org/2011/your-jquery-now-with-less-suck/.
Specifically:
Event delegation on the table rather than on the rows.
$('table').on('click', 'tr.'+treeTable.parentClass, function () {
treeTable.toggleRowChildren($(this));
});
Cache the children selection.
Use the faster element selector followed by a slower filter on the .childClass
var childrenRows = $('tr', parentRow.parent()).filter('.'+childClass);