Set cursor after span element inside contenteditable div

In browsers other than IE <= 8, this will do it:

function placeCaretAfterNode(node) {
    if (typeof window.getSelection != "undefined") {
        var range = document.createRange();
        range.setStartAfter(node);
        range.collapse(true);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

However, some browsers (notably WebKit-based ones) have fixed ideas about which positions in the document are valid for the caret and will normalize any range you add to the selection to comply with those ideas. The following example will do what you want in Firefox and IE 9 but not in Chrome or Safari as a result:

http://jsfiddle.net/5dxwx/

None of the workarounds are good. Options include:

  • add a zero-width space character after the span and select it
  • use an <a> element instead of a <span> because WebKit makes an exception for <a> elements

Leave a Comment