I always use:
What is the opposite of X ?
But today I came across:
What is the opposite word for X ?
Are the both grammatical?
Thank you.
Yes, both are grammatical, but the second should be punctuated
What is the opposite word to "X."
You need to understand the distinction between the use and the mention of a word.
https://en.m.wikipedia.org/wiki/Use–mention_distinction