Through spectroscopy. Each atom in a gas absorbs and emits light at very specific and unique frequencies. Heating up a gas causes it to glow at these frequencies. If you put the light from a mercury lamp, for example, through a prism there will not be a rainbow. There will only be specific bands of light at certain colors.
On the other hand, white light comes from the sun. The inner part of the sun creates white light as it isn't just a gas state (this specific choosing of frequencies is a gaseous phenomenon) but the atmosphere of the sun is a gas. So when the white light passes through it, it absorbs specific frequencies specific to the elements in the gas. These get scattered (released at random directions) and so many of them don't reach our telescopes. So in a rainbow from stars (including the sun) have dark bands at specific frequencies. You need equipment to focus and see the spectrum closely to notice this. But the missing frequencies are the EXACT frequencies that the gas of the sun's atmosphere would release if heated in a lamp.
So based on what light is emitted (in gas bulbs) or missing from a spectrum (from stars) we can tell what elements are present there.