I am working on a project for which i need to get the selected text inside an iframe the selected text itself can cross multiple spans inside the iframe i dont need to get the text itself but i need to know which spans did the text cross, all spans have ids from 1~ until the end of the page so they are all accessible via the id attribute all i need is to get all the ids of the spans which the selected text crosses, i have looked around google but didnt seem to find someone with the same problem
Asked
Active
Viewed 200 times
0
-
Not an *answer*, so I'll comment: Getting selections cross-browser is a pain, recommend using a library like Tim Down's [Rangy](http://code.google.com/p/rangy/). – T.J. Crowder May 12 '12 at 07:25
-
I can get the selection itself using javascript window.getSelection but it only gets the selected text, if i could get the selected text including the html itself my problem would be solved since i could parse the result to detect opening tags and get the ids out of them, but i am still looking into it – Ronin May 12 '12 at 07:37
-
What JS code are you using to get content? – Arnaud May 12 '12 at 07:49
1 Answers
0
Here's an answer for getting nodes in a range that will work for all major browsers except IE < 9, although you'll need to get the selected range yourself:
https://stackoverflow.com/a/7931003
For a cross-browser solution, you could use my Rangy library as follows, assuming you have a reference to your iframe in a variable called iframe
:
var sel = rangy.getIframeSelection(iframe);
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var spans = range.getNodes([1], function(element) {
return element.tagName.toLowerCase() == "span";
});
// spans is now an array of selected or partially selected <span>
// elements. Spans inside other spans are not included.
}