JSFiddle - React, Tailwind, and code Playground
HTML
<div id="testDiv" contentEditable="true">
Hey, click the button then hit space.
<br>
</div>
<button id="button">Set caret at end</button>
JavaScript
function placeCaretAtEnd(el) {
el.focus();
if (window.getSelection){
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
range.setEndAfter($(el).find('br')[0]); //only for FF, fiddle does not have browser check
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
}
$('#button').on('click', function() {
placeCaretAtEnd($('#testDiv')[0]);
});