Fix range exception due to nextElement being nil