contenteditable, set caret at the end of the text (cross-browser) contenteditable, set caret at the end of the text (cross-browser) javascript javascript

contenteditable, set caret at the end of the text (cross-browser)


The following function will do it in all major browsers:

function placeCaretAtEnd(el) {    el.focus();    if (typeof window.getSelection != "undefined"            && typeof document.createRange != "undefined") {        var range = document.createRange();        range.selectNodeContents(el);        range.collapse(false);        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();    }}placeCaretAtEnd( document.querySelector('p') );
p{ padding:.5em; border:1px solid black; }
<p contentEditable>foo bar </p>