There is a span element with contenteditable="true" . Some HTML content can be inserted into it from the clipboard. Before the insertion itself, the content is processed and only then it needs to be inserted at the cursor position or instead of the selected fragment. Those. we have about the following:

 document.querySelector('span[contenteditable=true]').addEventListener('paste', function(e){ e.preventDefault(); var content = e.clipboardData.getData('text/html'); // дальше я обрабатываю content, удаляя разные ненужные атрибуты // ... // и потом вставляю var selection = document.getSelection(); var range = selection.getRangeAt(0); range.deleteContents(); var node = document.createTextNode(content); range.insertNode(node); selection.removeAllRanges(); selection.addRange(range); }); 

Since when inserting I don’t need to wrap the content in additional tags, I use document.createTextNode() and not .createElement() . But the problem is that with createTextNode at the moment of inserting the content, all its HTML tags are visible, and they do not need to be displayed.

Is there any solution to this problem? In addition to reloading the page of course, this is in a pinch if there is no other solution.

    1 answer 1

    Found a simple solution on the English SO

    Instead

     var selection = document.getSelection(); var range = selection.getRangeAt(0); range.deleteContents(); var node = document.createTextNode(content); range.insertNode(node); selection.removeAllRanges(); selection.addRange(range); 

    need to insert with

     document.execCommand('insertHTML', false, content); 

    It is strange that no one suggested ...