Remove formatting from a contentEditable div

Viewed 43806

I have a contentEditable Div and I want remove any formatting especially for copy and paste text.

9 Answers

Try <div id="editableDiv" contentEditable="plaintext-only"></div>

I know it's been a while, but I had the same problem. On my case, it's a GWT application to make it even worse. Anyway, resolved the problem with:

var clearText = event.clipboardData.getData('text/plain');
document.execCommand('inserttext', false, clearText);

See: https://jsfiddle.net/erikwoods/Ee3yC/

I preferred "inserttext" command instead of "insertHTML", because the documentation says it's exactly to insert plain text, so seems more suitable. See https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

Just for my later life. ;)

styles.css

/* Not easy to look exactly like input field: */
/* https://stackoverflow.com/a/8957518/1707015 */
.contenteditable_div {
    /* box-shadow: 1px 1px 1px 0 lightgray inset; */
    background-color:#dddddd;
    overflow-wrap:break-word;
    padding:3px;
}

index.html

<!-- Firefox doesn't support contenteditable="plaintext-only" yet! -->
<div class="contenteditable_div" contenteditable="true" id="blubbi">abc</div>

script.js

// Optional: Copy font from other input field:
// $('#blubbi').css('font', $('#blubbi_input_field').css('font'));

$('.contenteditable_div').on('input', function(){
    // problems with setting cursor to beginning of div!
    // this.innerHTML = this.innerText;
    $(this).text($(this).text());
});

Keep in mind that this solution doesn't support or care about line breaks.

And keep in mind that setting the text like this will set the cursor to the beginning of your contenteditable div - while you are typing. Still a good solution if you need it only for copy & paste. Please write a comment if you have an easy solution for this "reverse typing problem" (under 10 lines of code please). ;)

Tested on Firefox 89, Chrome 90 and Safari 14.

Related