Set focus on div contenteditable element
Old post but none of the solutions worked for me. I figured it out eventually though:
var div = document.getElementById('contenteditablediv');
setTimeout(function() {
div.focus();
}, 0);
In modern browsers you can use:
var p = document.getElementById('contentEditableElementId'),
s = window.getSelection(),
r = document.createRange();
r.setStart(p, 0);
r.setEnd(p, 0);
s.removeAllRanges();
s.addRange(r);
But if your element is empty I got some strange problems so for empty elements you can do this:
var p = document.getElementById('contentEditableElementId'),
s = window.getSelection(),
r = document.createRange();
p.innerHTML = '\u00a0';
r.selectNodeContents(p);
s.removeAllRanges();
s.addRange(r);
document.execCommand('delete', false, null);
After deleting nbsp cursor stays inside p element
P.S. just ordinary space doesn't work for me