views:

31

answers:

1

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 into xxxxx.

+1  A: 

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;
    }
}
Tim Down
I can't believe it's that simple. It works. Thanks!
Judy