The goal is to group elements starting with different heading levels into sections nested according to those levels.
Problem is similar to XSLT: moving a grouping ht
I would simply let the function group by the current level and stop at the maximum level (which is 6 in HTML):
6
Obviously the level to search for could be provided as a parameter instead of hardcoding it in the stylesheet: