How to set caret(cursor) position in contenteditable element (div)? How to set caret(cursor) position in contenteditable element (div)? javascript javascript

How to set caret(cursor) position in contenteditable element (div)?


In most browsers, you need the Range and Selection objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:

function setCaret() {    var el = document.getElementById("editable")    var range = document.createRange()    var sel = window.getSelection()        range.setStart(el.childNodes[2], 5)    range.collapse(true)        sel.removeAllRanges()    sel.addRange(range)}
<div id="editable" contenteditable="true">  text text text<br>text text text<br>text text text<br></div><button id="button" onclick="setCaret()">focus</button>