Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select a text range in CKEDITOR programatically?

Problem:

I have a CKEditor instance in my javascript:

var editor = CKEDITOR.instances["id_corpo"];

and I need to insert some text programatically, and select some text range afterwards.

I already did insert text through

editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');

But I need to select (highlight) the word "foobar", programatically through javascript, so that I can use selenium to work out some functional tests with my CKEditor plugins.

UPDATE 1:

I've also tried something like

var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);

But doesn't work at all!

How can I do that?

I think that

selection.selectRange()

could do the job, but I'could not figure out how to use it. There are no examples over there :(

like image 212
Gabriel Falcão Avatar asked Dec 09 '10 17:12

Gabriel Falcão


1 Answers

Get current selection

var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();

Change the selection to the current element

var element = sel.getStartElement();
sel.selectElement(element);

Move the range to the text you would like to select

var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
    ranges[0].setStart(element.getFirst(), startIndex);
    ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
    sel.selectRanges([ranges[0]]);
}
like image 70
Siva Avatar answered Sep 22 '22 12:09

Siva