Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace selected text in contenteditable div

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.

like image 584
Judy Avatar asked Oct 22 '10 14:10

Judy


1 Answers

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;     } } 
like image 59
Tim Down Avatar answered Sep 17 '22 13:09

Tim Down