Search code examples
javascripthtmlcontenteditablecaretinserthtml

insertHTML in the caret position without creating object


I have contenteditable div, and span with text inside.

<div contenteditable="true"><span> Some text.. </span></div>

I need insert in place of caret closing and opening span tags. Like:

<div contenteditable="true"><span> Some </span><span> text.. </span></div>

I tried to make it by insertHTML:

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

It works in Crome, but Firefox makes span object and insert here (inserts a valid html). It turns out:

<div contenteditable="true"><span> Some <span></span> text.. </span></div>

Does anyone know how to split the span tag inside contenteditable div? Thanks in advance


Solution

  • You could just use the innerHTML property to insert any HTML code, here's an example using javascript:

    document.getElementById("myDiv").innerHTML = "<span>Here is the new Content!</span>";
    

    And give your div the id="myDiv".