Do you mean that the code does not work for you because there are master/detail rows on the second level of the Grid too? If so, you can make sure that you are querying the rows from the parent Grid only, for example:
expandedRowsLength = $(
allRowsLength = $(
If this does not work, please share a Dojo, which demonstrates the exact problem.
Telerik by Progress