Friday, May 17, 2024
167
rated 0 times [  170] [ 3]  / answers: 1 / hits: 48124  / 14 Years ago, fri, october 22, 2010, 12:00:00

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.


More From » contenteditable

 Answers
9

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;
}
}

[#95208] Wednesday, October 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyquandaquanl

Total Points: 122
Total Questions: 109
Total Answers: 101

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;