Consider this bit of HTML when rendered in a web browser:
<p contenteditable="true"><span style="font-weight:bold;">Bold</span>.</p>
In Firefox 66 and Edge 17, highlighting all five characters of text (i.e., including the full stop) and typing the word "New", for example, results in the following markup:
<p contenteditable="true"><span style="font-weight:bold;">New</span></p>
However, if you do the same thing in Chrome 73, you get:
<p contenteditable="true"><b>New</b></p>
Chrome seems to have decided to replace the span with a b element to achieve the same visual effect.
Is there any way to stop this happening? I have a text editor that is getting very confused by this behaviour.
You can play with this
<p contenteditable="true"><span style="font-weight:bold;">Bold</span>.</p>
Note: If all the text is within the span (so no full stop in this example), the b element is not created.
You are right Chrome decide to replace the new text with a similar styling
so what you need to block chrome from doing that is Document.execCommand() and it will keep the previous element before deletion with previous styling.
so the command you need is styleWithCSS
which replace what inside contentEditable
with style.
styleWithCSS
Replaces the useCSS command. true modifies/generates style attributes in markup, false generates presentational elements.
document.execCommand('styleWithCSS', false, 'true')
document.execCommand('styleWithCSS', false, 'true')
<p contenteditable="true">
<span style="font-weight:bold;">Bold</span>.</p>