views:

608

answers:

1

Hello,
I'm trying to set the caret position in a contenteditable div layer, and after a bit of searching the web and experimenting I got it to work in firefox using this:

function set(element,position){
    element.focus();
    var range= window.getSelection().getRangeAt(0);
    range.setStart(element.firstChild,position);
    range.setEnd(element.firstChild,position);
}

[...]

set(document.getElementById("test"),3);

But in Chrome/webkit it selects all of the content in the div. Is this a bug with webkit or am I doing something wrong?
Thank you in advance.

+1  A: 

The offset of a Range boundary within a node is only a character offset if the node is a text node. If the node is an element, the offset is the number of child nodes prior to the boundary.

For example, if you have HTML

<div id="myDiv">One <b>two</b> three</div>

... and you create a Range as follows:

var range = document.createRange();
var myDiv = document.getElementById("myDiv");
range.setStart(myDiv, 1);
range.setEnd(myDiv, 1);

... you'll get a Range that starts and ends immediately after the first child of the div, which is a text node:

<div id="myDiv">One |<b>two</b> three</div>
Tim Down