The original code was looping through _all_ the children of the menu items. So the calculation of _i_ did not reset at each menu item. The proposed code below does this my looping through top menu items, then counting the children _li_ elements.