For stars at least, the answer is absorption spectroscopy. Different frequencies of light have different energies, and each element has particular frequencies of light it's particularly good at absorbing because the energy of the light matches the energy differences between different orbits of electrons (in quantum…