Javascript: I can get the text of a selection, now how do I get the text outside the selection?
- by DavidR
I have a bit of code that returns the text of a selection and I can assign that string to a variable, but now all I need are two variables, one for the text before the selection and one for the text after the selection.
Here is the code for getting the selection:
function findSelection(){ //returns the selection object.
var userSelection;
if (window.getSelection) {userSelection = window.getSelection();} // Mozilla Selection object.
else if (document.selection){userSelection = document.selection.createRange();} //gets Microsoft Text Range, should be second b/c Opera has poor support for it.
if (userSelection.text){return userSelection.text} //for Microsoft Objects.
else {return userSelection} //For Mozilla Objects.
}
Then I find the anchorOffset and focusOffset to find the caret positions. I tried using these to modify a range object, like this:
var range = document.createRange();
range.setStart(textdiv,0);
range.setEnd(textdiv,5);
Where textdiv is a variable holding the last div the user clicked on. The problem is firefox just gives me a "Security error" code: "1000" at the line range.setStart(textdiv,0);.
Is there an easier way to go about doing this? I really just need the text and nothing more.