2
<div contenteditable="true">
    abcde<img src="abc.jp" />fg
</div>

$('div').append('<img src="abc.jpg" />'); //this will append img at end of text

I try to add an image into div in position 6

Is any way to append image in position?

Benjamin W
  • 2,658
  • 7
  • 26
  • 48

2 Answers2

6

get the text of the div split it at the specified position and concatenate it agian. Then override the html of the div:

var a = $.trim($('div').text());
var b = '<img src="https://jsfiddle.net/img/logo.png" />';
var position = 5;
var output = a.substr(0, position) + b + a.substr(position);
$('div').html(output);

Example


Notes

Using .substr() seems to be faster than .splice

I use $.trim() to avoid a wrong position count due to whitespace or linebreaks

The position is set to 5 because .substr() starts counting at 0

Community
  • 1
  • 1
empiric
  • 7,825
  • 7
  • 37
  • 48
0

Wrap your text within paragraph tags then you can append the img after the paragraph:

<div contenteditable="true">
    <p>abcde</p><span>fg</span>
</div>

$('div p').append('<img src="abc.jpg" />');
Pixelomo
  • 6,373
  • 4
  • 47
  • 57