Reputation: 1911
I have a div with contenteditable
set. This div contains an inner div like so:
<div contenteditable="true" class="key">
<div class="innerKey">276</div>
</div>
The odd editable div structure comes about from the need for other functionality.
How would I go about setting the caret position to the start of the content of the inner div using javascript?
Upvotes: 2
Views: 2817
Reputation: 324507
In browsers other than IE < 9, you can do this pretty simply, assuming for brevity that you added an id of "innerKey" to the inner <div>
:
var sel = window.getSelection();
var innerDiv = document.getElementById("innerKey");
var innerDivText = innerDiv.firstChild;
sel.collapse(innerDivText, 0);
jsFiddle: http://jsfiddle.net/Jaj6t/5/
If you need to support IE < 9, you can use my Rangy library to provide the cross-browser DOM Range and Selection support.
Upvotes: 2