1

I am not able to figure out, how to highlight a selected text in an editable div (when it contains many tags (nested) in it).

If I could get the exact position from where selection starts (index in the editable div, innerHTML), I could add a font tag over there with background color style (giving the effect of highlight). But I am not able to figure out a reliable way to get the index from where the selection starts.

My sample code is at: Sample.

"window.getSelection();" method gives me complete text of what has been selected, including nested tags (if I use innerHTML on it). Thus all I need is a reliable way to calculate the start index from where selection is starting.

Any help/reference is greatly appreciated.

Edit: Suppose my oDiv has content: <br><br><h2>I am H2, Title</h2>

And say I select H2 above, I need starting index as: 19 (counting all the tags inside oDiv). How can I get that? I need it to work for arbitrary deep nesting.

user1953366
  • 1,341
  • 2
  • 17
  • 27
  • possible duplicate of [Select all DIV text with single mouse click](http://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click) – Dylan Corriveau Mar 22 '15 at 23:48
  • Thanks Dylan, but I am not able to figure out the connection. In the link you mentioned current element is added to the range (and element ID is being passed as function). In my case, I want to know exactly from which position the selection started and use that to insert a background color tag to highlight. – user1953366 Mar 24 '15 at 19:38
  • It is dupe of: http://stackoverflow.com/questions/2584301/getselection-surroundcontents-across-multiple-tags I got it working (at least in chrome) – user1953366 Apr 24 '15 at 18:20

1 Answers1

3

var r = window.getSelection().getRangeAt(0); - gives the range inside the selection.

r.startOffset, r.endOffset - gives you the bounds of the range in selection.

If the div you are interested in has a id then you can get the element by:

var objDiv = document.getElementById("divId");
var r = document.createRange();
r.selectNodeContents(objDiv);

If the element doesn't have an id, then there are other means to get the object. See here: Finding HTML Elements

And now you can get the bounds of range r using the startOffset and endOffset properties.

yasouser
  • 5,113
  • 2
  • 27
  • 41
  • Thanks for your answer. I need the index wrt the editable div. have edited my questions. – user1953366 Mar 25 '15 at 19:35
  • Tried and r.startOffset it always gives 0, r.endOffset also return fixed value depending on the Div contents (irrespective of what i select). I guess it is giving no of elements in the div – user1953366 Mar 26 '15 at 18:05