I am using Javascript to calculate the offset and length of a substring selected on my page. This gets stored somewhere and later, when I hover over the text I want to highlight certain words in it using that offset and length in jQuery. Here is the basic code used for the highlight:
content = $("#reader").html();
newContent = content.substring(0,offset)+'<font style="color: red;">'+content.substring(offset,offset+length)+'</font>'+content.substring(offset+length,content.length);
content = $("#reader").html(newContent);
Now my problem is this: the offset and length are calculated over what is displayed on the screen. The actual HTML code, however, may also contain <p> or other tags. As a result, the text that I highlight gets "shifted", depending on the amount of HTML code present.
What is the easiest way to solve this?