Javascript: Set selection (cursor position) in a contenteditable div

In textareas we have selectionStart and selectionEnd. In divs with the contenteditable attribute we must use window.getSelection().

The window.getSelection() function returns an object. This object has a anchorNode property. This is the node where the selection is taking place.

The collapse() method on the Selection object allows you to collapse the selection into a position. And so you can move the cursor.

collapse() takes two arguments. The node of the selection. And the position of the cursor in that node. If you have a text element as the first parameter, the second parameter is the position in that text.

The below moves the cursor to the third position in a text element inside a contenteditable div when it's initially focused.

<div contenteditable="true">i am editable</div>
the_above_div.onfocus = e => {
  var sel = window.getSelection()
  var selected_node = sel.anchorNode
  // selected_node is the text node
  // that is inside the div
  sel.collapse(selected_node, 3)
}
i am editable



javascript
I've removed disqus comments
Instead, press this
to express thanks
So far, 1 people have pressed the octopus