Search code examples
javascripthtmlcontenteditable

Insert span in contentEditable with document.execCommand('insertHTML',


I'm working on a rich content editor. Configuration is set to adding a <p> tag as paragraph separator:

document.execCommand('defaultParagraphSeparator', false, "p");

I have to insert special <span contenteditable='false'> sections:

document.execCommand('insertHTML', false, "<span contenteditable='false'>...</span>");

Insertions are not done as expected.

I expect :

<p>something <span>...</span></p>

I got :

<p>something </p>
<span>...</span>

I can't figure out why the span tag is not inserted in the p tag. Any idea?


Solution

  • execCommand has a history of inconsistency and bugginess across different browsers. Nowadays, execCommand is obsolete:

    This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

    Source : https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

    I suggest you to read this page on best alternatives : https://medium.com/@jitubutwal144/three-different-ways-to-build-inline-content-editor-using-javascrpit-d58c2edac9cb