I have the below code
<div>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
</div>
with this jquery
jQuery('p:nth-child(5)').after('</div><div><img src="http://dummyimage.com/100x100/fff/000"></div><div>');
I want my output to be this.
<div>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
</div><div><img src="http://dummyimage.com/100x100/fff/000"></div><div>
<p>some text</p>
<p>some text</p>
</div>
instead I am getting this.
<div>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p><div><img src="http://dummyimage.com/100x100/fff/000"></div><div></div>
<p>some text</p>
<p>some text</p>
</div>
see this fiddle for example.
Where am I going wrong here? Or should I be using something other than .after() to do this?
You can’t use unbalanced HTML to change the DOM tree like that. jQuery requires a balanced block of HTML to be supplied, since each time you pass in HTML like this it’s creating a detached DOM tree, not merely inserting the HTML snippet into the source code.
You’ll need to create a new
<div>to hold the image, and another to hold the remaining<p>elements, and then use.append()to move the excess elements from the first div into the latter, e.g.:See http://jsfiddle.net/alnitak/Z8LR3/