1. He ran for class leader.

2. He ran for a class leader.
3, He ran for the class leader.

(Which one is grammatical?)

All are correct under different circumstances.

1 means he is running (is a candidate) for one of several class leadership positions.

2 and 3 have different meanings, depending on context.

2 could mean that he ran a race on behalf of one of the class leaders OR it could mean that he was a candidate for one particular class leadership positions.

3 could mean that he ran a race on behalf of the topmost class leader (maybe, the president) OR it could mean that he was a candidate for the top class leadership position (maybe president).