Remove formatting from a contentEditable div

41,372

Solution 1

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>

Solution 2

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.

Solution 3

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>

Solution 4

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

Solution 5

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

Share:
41,372
Garth Humphreys
Author by

Garth Humphreys

Creator of things at konec.ky

Updated on April 29, 2021

Comments

  • Garth Humphreys
    Garth Humphreys about 3 years

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

  • Garth Humphreys
    Garth Humphreys almost 13 years
    How would I remove formatting from the copy and pasted text by using innerText? I thought I either have to set something on the contentEditable Div or remove the formatting from the clipboard before the text is pasted. Thanks for your help.
  • Sam Dutton
    Sam Dutton almost 13 years
    Sorry didn't understand that you wanted to paste text into the editable div. See edited answer for suggestion to remove formatting.
  • Tim Down
    Tim Down almost 13 years
    That's going to remove formatting from the whole editable div, not just the stuff pasted in. If that's what the OP wants then he could use a textarea instead.
  • ThE uSeFuL
    ThE uSeFuL almost 12 years
    I'm building a rich text editor and want to implement a function which removes the formatting of a selected text. Any idea how to do this? (I'm using a contentEditable div)
  • Doug Wolfgram
    Doug Wolfgram over 10 years
    This is genius! Just saved my bacon.
  • Doug Wolfgram
    Doug Wolfgram over 10 years
    Is there any way to do this and preserve linefeeds?
  • Eric Wood
    Eric Wood over 10 years
    Just a warning, this strips out newlines. I wouldn't recommend this solution.
  • user2173353
    user2173353 over 8 years
    Seems to work great and it preserves newline formatting. Thanks! :)
  • user2173353
    user2173353 over 8 years
    For some reason I get an error of “Invalid argument.” on IE8 with this. I had once the impression it was working there, but probably I was wrong. I don't know if some other event (or something) screws things up... Good otherwise. :)
  • caub
    caub almost 8 years
    chrome has contenteditable="plaintext-only" but using textContent is cross-browser
  • Paul McClean
    Paul McClean almost 7 years
    The key to this answer is the use of the clipboardData.getData("text/plain") API. Pretty self-explanatory I thought. More info on the clipboard API here: w3.org/TR/clipboard-apis
  • Azametzin
    Azametzin about 4 years
    It was an automatic message from a review queue. I believe you. I deleted the message.
  • andymel
    andymel about 4 years
    Nice! Can someone add some words about how 'document.execCommand("insertHTML", false, text);' works? I call a method on document but somehow it inserts at "the current position"...
  • JustinStolle
    JustinStolle almost 4 years
    I would love to use this, but it is not (yet) widely supported. caniuse.com/…
  • qräbnö
    qräbnö about 3 years
    No support in Firefox. At the moment you can't get around true if you want to support all browsers and have to make friends with a Javascript solution. :(
  • Mitch Talmadge
    Mitch Talmadge almost 3 years
    This works for copy-paste, but I found that users can still abuse the field via drag-and-drop.