1

How can I set a text selection in a contenteditable div based on the position in the source code?

An example:

I've got the following html source code for a html element:

A sentence <div>with <span class='foo'><b>html</b>&nbsp;content</span>!</div>

This sentence has 77 characters. How can I make a selection of the word content with the function call setSelection(parentDiv, 56, 63). So I'm searching for a solution for this:

var editor = document.getElementById("editor");

function setSelection(parentDiv, start, end) {
    // how can I set the selection?
}

setSelection(editor, 16, 21); // this should select "with"
setSelection(editor, 56, 63); // this should select "content"

Javascript Contenteditable - set Cursor / Caret to index goes in the right direction, but there only the characters of text nodes will be count.

Only modern browsers will be supported (IE >= 9) and the use of jQuery (or other libraries) is also possible.

Here is the jsfiddle.

Community
  • 1
  • 1
friedi
  • 4,350
  • 1
  • 13
  • 19

0 Answers0