1

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?

3 Answers 3

1

This is not easily solvable. You shouldn’t calculate offset and length over the text, but over the HTML, if you want to work on the HTML afterwards. However, inserting HTML tags somewhere into an existing HTML string may lead to invalid nesting. And finally, you lose state like attached event handlers if you re-insert nodes as HTML code.

Sign up to request clarification or add additional context in comments.

Comments

1

use

$("#reader").text()

instead of $("#reader").html() to get the text out of your content

Comments

0

I'd strip tags or use DOM methods - like. .nodeType, .nodeValue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.