The Codesee The Codesee - 2 months ago 12
HTML Question

Multiple elements with same class - only insert after last one

I am using the JQuery function

.after
function to insert an element after another element.

The page structure looks like this:

<div class="example"></div>
<div class="example"></div>
<div class="example"></div>


I am using this line of code to insert a
<p>
element:

$('.example').after('<p>Hello</p>');


The issue is that
<p>Hello</p>
is being inserted after every
<div class="example"></div>
element - I only want it to be inserted after the last
<div class="example"></div>
element.

Answer

Try

$('.example').last().after('<p>Hello</p>');

Comments