1

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

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • So, what you really want is to separate each word into it's own `` tag? Are you OK with using third party libraries like jQuery? – Tomas Aschan Oct 24 '14 at 10:56
  • @TomasLycken, Ohhh. I don't want separate each word into `` tags. That's what I need: http://jsfiddle.net/cwm3tbtu/ but it doesn't work in firefox. –  Oct 24 '14 at 11:43

1 Answers1

2

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".

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • I need to have the caret remains in the same place. In this case, caret jumps to the end –  Oct 24 '14 at 11:01
  • @VasyaShmarovoz I don't really understand what you mean by that but you could also give the span elements an id and insert the text with innerHtml inside the spans, if that's what you're asking for? – sebbzzz Oct 24 '14 at 11:04
  • @VasyaShmarovoz Yes in fact, it's not clear enough but you just need to initially put an empty div where you want to add your content and use innerHTML to fill it . – cнŝdk Oct 24 '14 at 11:11
  • @chsdk, How do I divide the span in the place where there is a caret? –  Oct 24 '14 at 11:28
  • @VasyaShmarovoz, to devide the span use the [JavaScript String split() Method](http://www.w3schools.com/jsref/jsref_split.asp) [here is an example](http://stackoverflow.com/questions/8103485/split-html-in-divs-with-javascript-jquery-based-on-hr-tags), but getting the caret position is the big deal of it. Take a look here, there are some issues: [First](http://stackoverflow.com/questions/5951886/how-to-get-caret-position-within-contenteditable-div-with-html-child-elements) and [Second](http://stackoverflow.com/questions/3454152/cross-browser-selection-range-library) . – cнŝdk Oct 24 '14 at 11:43