Get selection offsets in JS/HTML with formatting information

I am building a web interface for annotating texts.
The user should select a portion of the text (using the mouse) and write some side notes about it. When I save the annotation, I need to keep the offsets of the selected text. Note that the text is taken from a TXT file that may include spaces, tabulations, newlines, etc.

Now I put the text into a <pre> tag and call the Selection object in JS to get the offsets. By using a <pre> container, I have perfect correspondence between the offsets of the selection and the offsets in the TXT file.

Now I need to add some formatting information on this text (for instance, highlight the portions of text already annotated by other users): if I add some <span>s with the background color, I mess the information about the selection and the offsets.

Any idea on how to deal with this problem?