2

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
behz4d
  • 1,819
  • 5
  • 35
  • 59

2 Answers2

2

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
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
$('.blah').on('click', function(){
    var new_add = '<div class="new">xxx</div>';
    $(this).parents('div.main').siblings('.main:last').append(new_add);
});

FIDDLE

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Wouldn't this also add to a previous comment? – casraf Jul 02 '13 at 08:02
  • Yes, it would. Your question didn't mention anything about that. – Barmar Jul 02 '13 at 08:05
  • this goes to the last .main and add it there, this should be before the another main and after `$(this).parent('.main').last(.reply)` – behz4d Jul 02 '13 at 08:06
  • Sorry, I based it on your code, not your words. I don't know how to get to the latest reply without crossing over into another main. – Barmar Jul 02 '13 at 08:08