I have a function that return an array (won't work in IE) with two elements
- the html code of what the user select inside a div (id=text)
- the range of the selection
In case the user select a simple string inside the text div the range return the correct values but when the user select a string inside an element child of div (div#text->p for example) range's values are related to the child element but i want them to be related to the parent (div#text)
Here there's a JsFiddle http://jsfiddle.net/paglia_s/XKjr5/: if you select a string of normal text or normal text + bolded text in the teatarea you'll get the right selection while if you select the bolded word ("am") you'll get the wrong one because the range is related to the child element.
There's a way to do so that the range is always related to div#text?
If you don't want to use a library here is a way which worked for me. The function returns the cursor offset relative to the textContent of the given node (not in relation to the sub nodes). Note: The current cursor position must lie in the given node or in any of its sub-nodes. It's not cross-browser compatible (specially not for IE), but I think it's not much work to fix that as well:
You could use my Rangy library and its new TextRange module, which provides methods of Range and selection to convert to and from character offsets within the visible text of a container element. For example:
rangeOffsets
has propertiesstart
andend
relative to the visible text insidecontainer
. The visible text isn't necessarily the same as what jQuery'stext()
method returns, so you'll need to use Rangy'sinnerText()
implementation. Example:http://jsfiddle.net/timdown/KGMnq/5/
Alternatively, if you don't want to use Rangy, you could adapt functions I've posted on Stack Overflow before. However, these rely on DOM Range and Selection APIs so won't work on IE < 9.