Home >Web Front-end >JS Tutorial >How to Programmatically Set the Caret Position in a ContentEditable Element?
Setting the caret position in a contenteditable div can be achieved using the Range and Selection objects. Here's how to set the caret to a specific position within the element:
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) }
Consider the following HTML:
<div><p>When you click the "focus" button, the JavaScript function setCaret() is invoked, placing the caret at the fifth character of the second line of text.</p></div>
The above is the detailed content of How to Programmatically Set the Caret Position in a ContentEditable Element?. For more information, please follow other related articles on the PHP Chinese website!