Get the selected text from an FCKEditor instance

Posted Apr. 07, 2009 in FCKEditor

FCKEditor is an in-browser WYSIWYG HTML editor. Roughly every 10 days I post a tutorial or example code using FCKEditor in the Javascript section of this blog and in this post look at how to get a copy of the text that is currently selected in the editor. The next FCKEditor post on April 17th will show how to get the HTML of the current selection.

Getting the selection as plain text

The FCKEditor API Documentation has a section which is titled "Working with the selection in the editor: Use the Selection Object" but then it doesn't appear to document the selection object anywhere. I did a bit of searching and came up with the following solution that uses a combination of the selection object and other Javascript functions.

The parameter "instance_name" is the name of the FCKeditor instance.

function get_selection_plain(instance_name) {

    var oFCKeditor = FCKeditorAPI.GetInstance(instance_name);
    var selection = (oFCKeditor.EditorWindow.getSelection ? oFCKeditor.EditorWindow.getSelection() : oFCKeditor.EditorDocument.selection);
    if(selection.createRange) {
        var text = selection.createRange().text;
    else {
        var text = selection;
    return text;


The createRange test is needed to make sure the code works in both Internet Explorer and in other browsers. IE uses the selection.createRange() part and other browsers use the other part.

If the current selection in the FCKEditor contained the following HTML:

<p>This is line 1</p>
<p>This is <a href="">line</a> 2<br />
  This a line break in line 2</p>
<p>This is line 3</p>

In Firefox, Safari (tested on Windows only) and Chrome the value returned should be this:

This is line 1

This is line 2
This a line break in line 2

This is line 3

In Internet Explorer it will be this:

This is line 1
This is line 2
This a line break in line 2
This is line 3

In Opera (tested on 9.64) it will run it all one line like this:

This is line 1This is line 2This a line break in line 2This is line 3

but if you click the "Source" button and click it again to go back to the HTML editor then it will show it as Firefox does.

So although it is easy enough get the text selection, the formatting will not be consistent across browsers. It would therefore pay to use this function with caution.

Related posts: