Reputation: 2848
<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?
Upvotes: 2
Views: 1059
Reputation: 7878
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);
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
Upvotes: 6
Reputation: 6737
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" />');
Upvotes: 0