Benjamin W Benjamin W - 1 year ago 106
Javascript Question

jquery append() in string position

<div contenteditable="true">
abcde<img src="" />fg

$('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?

Answer Source

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="" />';
var position = 5;
var output = a.substr(0, position) + b + a.substr(position);



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download