Remove formatting from a contentEditable div
You can add a listener to the "paste" event and reformat the clipboard contents. Like so:
let editableDiv = document.querySelector('div[contenteditable="true"]');
editableDiv.addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
Here another example for all containers in the body:
let allEditableDivs = document.querySelectorAll('div[contenteditable="true"]');
[].forEach.call(allEditableDivs, function (el) {
el.addEventListener('paste', function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
}, false);
}
Saludos.
Was looking for answer to this for ages and ended up writing my own.
I hope this helps others. At the time of writing this it appears to work in ie9, latest chrome and firefox.
<div contenteditable="true" onpaste="OnPaste_StripFormatting(this, event);" />
<script type="text/javascript">
var _onPaste_StripFormatting_IEPaste = false;
function OnPaste_StripFormatting(elem, e) {
if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
}
else if (e.clipboardData && e.clipboardData.getData) {
e.preventDefault();
var text = e.clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
}
else if (window.clipboardData && window.clipboardData.getData) {
// Stop stack overflow
if (!_onPaste_StripFormatting_IEPaste) {
_onPaste_StripFormatting_IEPaste = true;
e.preventDefault();
window.document.execCommand('ms-pasteTextOnly', false);
}
_onPaste_StripFormatting_IEPaste = false;
}
}
</script>
Have you tried using innerText?
ADDED:
If you want to strip markup from content pasted into the editable div, try the old hack of creating a temporary div -- see example below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Strip editable div markup</title>
<script type="text/javascript">
function strip(html) {
var tempDiv = document.createElement("DIV");
tempDiv.innerHTML = html;
return tempDiv.innerText;
}
</script>
</head>
<body>
<div id="editableDiv" contentEditable="true"></div>
<input type="button" value="press" onclick="alert(strip(document.getElementById('editableDiv').innerText));" />
</body>
</html>