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.