4

Here is my question:

When the user makes a selection in an article or in the editing area of a WYSWYG editor widget, the selection can span over multiple elements, like anchors, images, span tags... even block-level elements (but no table in my problem).

I know how to retrieve a Range object from the selection, but could not find a reliable solution to get the content text of the Range object.

I'm not looking for a solution for IE (its TextRange object has a .text property).

Thanks!

Luc125
  • 5,752
  • 34
  • 35

2 Answers2

4

Have you looked at the quirksmode article on Range?

Based on this article, you could create a method like this:

function getRangeText() {

    var userSelection;
    if (window.getSelection) {
        userSelection = window.getSelection();
    } else if (document.selection) {
        userSelection = document.selection.createRange();
    }
    var selectedText = userSelection;
    if (userSelection.text) {
        selectedText = userSelection.text;
    }
    return selectedText;
}

I tested this in FF5, Opera 11, Safari on the Mac, as well as IE6 and IE7. It's worth testing in the other IE browsers, but my guess is it works in them, as well.

Chris B
  • 598
  • 4
  • 6
  • Thank you for your answer and all the tests! I didn't know there could be an implicit string conversion for the Selection object (`userText = userSelection + ""`) – Luc125 Jun 25 '11 at 09:06
  • 1
    I hate this quirksmode article: the code has errors and it gets everywhere. The problem is that this function returns a string in IE < 9 (as you'd expect) and a `Selection` object in all other major browsers, which is no good if you're relying on getting a string. See my answer for a simpler, working function. Sorry to rant on your answer, @Chris: it's nothing personal and it's not your fault. – Tim Down Jun 27 '11 at 23:27
  • @Tim Down Yes, I had noticed that a `Selection` object could be returned; but the line ´var selectedText = userSelection;` gave me the idea that the automatic string conversion could be useful; I had always thought that it would only return something like `[object Selection]`. – Luc125 Jun 28 '11 at 07:54
2

This returns a string and works in all major browsers:

function getSelectionText() {
    var text = ""
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • +1, Thank you for the reliability of your code and the idea of checking `document.selection.type == "Text"` – Luc125 Jun 28 '11 at 08:02