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?

3
  • Not an answer to your question, but you should use <img> tags, not <im> Commented Nov 29, 2016 at 16:39
  • so you want to append the img after the text 'fg'? Commented Nov 29, 2016 at 16:42
  • no between abcde & fg Commented Nov 29, 2016 at 16:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Mahi just updated my answer to add that, remove the trim and you will see
@Mahi, between > and abc... there are characters, specifically '\n ', which must be accounted for.
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" />');

1 Comment

cant put tag, because it going to post to server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.