Moritz,
you can certainly do this in HTML, either using the PHP parser output or
Parsoid. Parsoid output makes it easier to identify math extension output.
If you need the wikitext for the heading, then Parsoid can also give you
the source offsets of the that in data-parsoid (see the dsr property in
there, it encodes startOffset, endOffset, startTagWidth, endTagWidth).
Gabriel