JSFiddle - React, Tailwind, and code Playground
HTML
<div contenteditable="true"><p>This is the first paragraph.</p><p>This is the second. Observe the DOM when we become one (place your cursor at the start or end of either and press backspace or delete respectively).</p><p>In Chrome, <span style="font-size: 16px;"> are inserted at the point where the two paragraphs are joined.</p></div>
<pre id="pre"></pre>
CSS
div, pre {
border: 1px solid gray;
padding: 10px;
line-height: 1.44;
}
pre {
margin-top: 10px;
max-width: 100%;
white-space: normal;
}
JavaScript
$(function() {
var checkForSpan = false;
$('div[contenteditable]').on("DOMNodeInserted",function(e) {
if( checkForSpan ) {
if(e.target.tagName == "SPAN" )Â {
checkForSpan = false;
var helper = $("<b>test</b>");
$(e.target).before(helper);
helper.after($(e.target).contents());
helper.remove();
$(e.target).remove();
}
}
});
$('div[contenteditable]').on("keydown keypress",function(e) {
if( !document.getSelection().isCollapsed ) {
saveSelectionState();
} else if(e.which==8 || e.which==46) {
saveSelectionState();
}
});
function saveSelectionState() {
checkForSpan = true;
}
$('div[contenteditable]').keyup(function() {
$('#pre').text($(this).html());
}).keyup();
});