4

I am attempting to put together a java script that, upon a user's selection of some text inside a specific div id, will return that selection's start and end indices ignoring internal html tags.

Consider the following example:

<p>Some text that will be ignored</p>
<div id="X">
    <p>Here is some text that should be considered</p>
    <p>Here is a bit more <span>tex</span>t in a separate paragraph but the same div id</p>
</div>

Now, If I highlight be considered. Here is and use

var currentRange = window.getSelection().getRangeAt(0);

console.log('startContainer\t'+currentRange.startContainer);
console.log('startOffset\t'+currentRange.startOffset);
console.log('endContainer\t'+currentRange.endContainer);
console.log('endOffset\t'+currentRange.endOffset);
console.log('textLength\t'+currentRange.toString().length);
console.log('text\t'+currentRange.toString())

I get startOffset:29 and endOffset: 4.

My Question:

Is it possible to keep track of which <p> tag I am inside of while using the Range() object? I will eventually have more html elements in this div tag, but want to be able to get the indices range of the selection as though it were all one string, ignoring all html elements inside.

Thanks for all the help!

AdrianV
  • 97
  • 6
  • http://stackoverflow.com/questions/5643635/how-to-get-selected-html-text-with-javascript this might help u – Ayyappan Sekar Aug 06 '13 at 07:07
  • [Not related] `currentRange.toString().split(/\s+/).join(" ")` might help you to ignore the tags. – Mr_Green Aug 06 '13 at 07:12
  • Thanks, I just found the rangy library, so I am trying to see if I can make use of it. – AdrianV Aug 06 '13 at 07:15
  • That is [`rangy`](https://code.google.com/p/rangy/) library. You may also want to look at `rangyinputs` library. – Mr_Green Aug 06 '13 at 07:16
  • right..so after playing around with ranpy, it doesn't seem to be doing more than what I have implemented already - highlight text for example by wrapping tags around the selected text. However, I require the actual indices of those phrases - which it does not appear to provide..at least from what I am seeing – AdrianV Aug 06 '13 at 08:18

0 Answers0