For example, I am having such html:

<span>"This is s"<strong>xy</strong>"z"<strong>ample</strong>" text"</span>

http://jsfiddle.net/6Lumh3av/

When I click in between "sxyzample" word from "This is sxyzample text" sentence, I want to select "sxyzample" word using range API's so that new range will be created with the following values.

range.startContainer.nodeType=3
range.startContainer.textContent= "This is sa" 
range.endContainer.nodeType=3
range.endContainer.textContent="mple"
range.startOffset=8
range.endOffset=5

I'm using window.getSelection(),range,nodes.

Code snippet is as follows.

<span class="clickable">"This is s"<strong>xy</strong>"z"<strong>ample</strong>" text"</span>

$(".clickable").click(function(e) {
s = window.getSelection();
var range = s.getRangeAt(0);
var node = s.anchorNode;
while (range.toString().indexOf(' ') != 0) {
    range.setStart(node, (range.startOffset - 1));
}
range.setStart(node, range.startOffset + 1);
do {
    range.setEnd(node, range.endOffset + 1);

} while (range.toString().indexOf(' ') == -1 && range.toString().trim() != 
'' && range.endOffset < node.length);
var str = range.toString().trim();
alert(str);
});​

0 Answers