replace selected text in contenteditable div

Judy picture Judy · Oct 22, 2010 · Viewed 37.1k times · Source

I have been looking high and low for an answer but failed.

Is there a cross-browser solution to replace selected text in contenteditable div?
I simply want users to highlight some text and replace the highlighted text with xxxxx.

Answer

Tim Down picture Tim Down · Oct 22, 2010

The following will do the job in all the major browsers:

function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = replacementText;
    }
}