This code would fit very nicely in a jstree plugin called accordion.