Added DOM checks to ensure elements exist before manipulation or reference.