I’m looking to wrap a cursor in span tags in a contenteditable div.
Example (cursor represented by |):
- Before:
The fox jumps |
- After:
The fox jumps <span>|</span>
Any attempt to modify the innerHTML results in the cursor being moved to the end of the line. I’d like it to be inserted in between the new HTML span‘s.
This isn’t possible cross-browser because of implementation issues. Attempting to place the caret within an empty inline element such as a
<span>in both WebKit and IE will actually place the caret immediately before the element. The following demonstrates this: it will do you what you expect in Firefox but not WebKit or IE.http://jsfiddle.net/8TTb3/1/
You can use a DOM Range and the Selection API to insert elements at the caret position, except in IE < 9 which does not support these and instead has its own API.
Code: