Fixes weird jquery bug

When next returns null, the hasClass further throws Untyped exception.

The fix checks for next first then follows the same logic.

Had a hard time reproducing this bug, seems to be coupled with box-layout and jquery.