Replace selected text in contenteditable div

I searched high and low for an answer, but could not.

Is there a cross-browser solution to replace the selected text in a contenteditable div? I just want users to select text and replace the selected text with xxxxx.

+27
javascript contenteditable
Oct 22 2018-10-22
source share
1 answer

The following will do the job in all 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; } } 
+59
Oct 22 2018-10-10
source share



All Articles