behz4d
behz4d

Reputation: 1849

jQuery insertAfter last item

I have:

<div class="main">
    <a class="blah">blah1</a>
</div>
<div class="main">
    <a class="blah">blah2</a>
</div>
<div class="main reply">
    <a class="blah">blah3</a>
</div>
<div class="main reply">
    <a class="blah">blah4</a>
</div>
<div class="main reply">
    <a class="blah">blah5</a>
</div>
<div class="main">
    <a class="blah">blah6</a>
</div>
<div class="main reply">
    <a class="blah">blah7</a>
</div>

on click of a.blah, I need to append something like <div class="new">xxx</div> to the latest .reply after the parent .main, it means it should find the latest .reply agter the parent of the a.blah, and it should not cross to another .main, here is what I coded (but not working):

$('.blah').on('click', function(){
    var new_add = '<div class="new">xxx</div>';
    $(this).parents('div.main').next('.main:last').append(new_add);
});

How should I fix this? Thanks

Upvotes: 2

Views: 7096

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Based on the comments

$('.blah').on('click', function(){
    var new_add = '<div class="new">xxx</div>';
    $(this).closest('.main').nextUntil('.main:not(.reply)').addBack().last().after(new_add);
});

Demo: Fiddle

  1. .closest() find the immediate ancestor matching the selector
  2. .nextUntil() finds all the .reply elements coming after the current .main without crossing over a .main without .reply
  3. .addBack() adds back the current parent, incase the next .main is not .reply
  4. .last() finds the last element from the matched set
  5. .after() inserts the passed element after the matched set of element

Upvotes: 2

Barmar
Barmar

Reputation: 780994

$('.blah').on('click', function(){
    var new_add = '<div class="new">xxx</div>';
    $(this).parents('div.main').siblings('.main:last').append(new_add);
});

FIDDLE

Upvotes: 0

Related Questions