Dash-ag-grid row group panel -- expand / collapse group levels

In my data I have “rowGroup” True for 5 different groups by default. (node.level 0 through 4.)
I have button code to collapse nodes that are on level 4 with the default grouping:

if (s.includes('btn-hide-trans')) {
            console.log('hide trans')
            gridApi.forEachNode((node) => {
                if (node.level === 4) {
                    gridApi.setRowNodeExpanded(node, false);

However, with the row group panel the user can change the row grouping, and thus the number of levels. So the code breaks.

What I would like to do instead is have 2 buttons: one for “Collapse Level” and one for “Expand Level”:

“Collapse Level”: This would find the highest level that exists (normally 4 by default) and collapse all nodes on that level. Equivalent to the existing code, but accounts for the user changing the grouping via the row group panel.

“Expand Level”: Same as above but expand highest level instead of collapse.

So really I just need to know, how can I get the highest current group level from the API when I press the button?
I can probably loop through all nodes and create a set, then get highest number, but that just seems bad.


To efficiently find the highest current group level in your data grid, you can indeed loop through all nodes, but instead of creating a set, you can keep track of the maximum level found. This approach is more efficient than creating a set, as it only requires a single pass through the nodes and does not require additional memory for the set.

Here’s how you can modify your button click handlers to find the highest level and either collapse or expand all nodes at that level:

function collapseOrExpandHighestLevel(collapse) {
    let highestLevel = -1;

    // Loop through all nodes to find the highest level
    gridApi.forEachNode((node) => {
        if (node.group) {
            highestLevel = Math.max(highestLevel, node.level);

    // Collapse or expand all nodes at the highest level
    if (highestLevel !== -1) {
        gridApi.forEachNode((node) => {
            if (node.level === highestLevel) {
                gridApi.setRowNodeExpanded(node, !collapse);

// Attach these functions to your buttons
document.getElementById('btn-collapse-level').addEventListener('click', () => collapseOrExpandHighestLevel(true));
document.getElementById('btn-expand-level').addEventListener('click', () => collapseOrExpandHighestLevel(false));

In this code:

  • The collapseOrExpandHighestLevel function takes a boolean argument collapse. If true, it collapses the nodes; if false, it expands them.
  • It first finds the highest level by looping through all nodes and keeping track of the maximum level found.
  • Then, it loops through the nodes again and collapses or expands nodes that are at the highest level.
  • Finally, attach these functions to your “Collapse Level” and “Expand Level” buttons.
1 Like