For each article on a page, I would like to insert an image at the very end of the last paragraph. My HTML looks like this:
<div class="storycontent">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
There may be several of those sections or only one. There is also an unknown number of <p></p> tags.
What I would like to do is insert an <img /> at the very end of the last <p> before the closing tag.
Here is what I have so far, but it is only appending the image tag to the very last <p> on the page, and not the last one in the storycontent <div>
jQuery('.storycontent').each(
function(){
jQuery(this).last('p').append(img);
//img is a var which contains an Image() element;
}
);
You’re misusing the last() method, which doesn’t take any argument and returns the last matched element. You should write something like:
Or:
Or even:
Also note that you cannot add the same element to the DOM multiple times, since the element will be moved into its new parent if it’s already part of the DOM. A simple solution is to clone() it, as the code above does.