user3653474
user3653474

Reputation: 3854

Remove parent and next-until Elements

I have a structure something like this:

  <div class="list_wrapper">  
    <div class="row mainrow">
    Main Row 
    <a href="javascript:void(0);" class="list_remove_button">Remove</a>
    </div> 
    <div class="row subrow"> 
    Sub Row 
    </div> 
    <div class="row subrow"> 
    Sub Row 
    </div> 
    <div class="row mainrow">
    Main Row 
    <a href="javascript:void(0);" class="list_remove_button">Remove</a>
    </div> 
    <div class="row subrow"> 
    Sub Row 
    </div>
    </div>

Here, after mainrow, subrow can be inserted it is not mandatory. Now if I delete mainrow then its subsequent subrow should also be deleted, for that I'm trying this code but it is not working, current element which is list_remove_button on click deletes the closest mainrow but not the siblings subrow (of mainrow):

 $('.list_wrapper').on('click', '.list_remove_button', function()
    {
       $(this).closest('div.row').remove();
       $(this).children('.subrow').remove();
    });

Upvotes: 0

Views: 54

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

  • Once you get the closest .mainrow using .closest()
  • use .nextUntil() to get the next-siblings
  • and use .addBack() to add back the initial $main to the stack - before .remove()ing them all

$('.list_wrapper').on('click', '.list_remove_button', function() {
  const $main = $(this).closest('.mainrow');
  $main.nextUntil('.mainrow').addBack().remove();
});
<div class="list_wrapper">
  <div class="row mainrow">
    Main Row 1
    <a href="javascript:void(0);" class="list_remove_button">Remove</a>
  </div>
  <div class="row subrow">
    Sub Row 1
  </div>
  <div class="row subrow">
    Sub Row 1
  </div>
  <div class="row mainrow">
    Main Row 2
    <a href="javascript:void(0);" class="list_remove_button">Remove</a>
  </div>
  <div class="row subrow">
    Sub Row 2
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Upvotes: 1

Related Questions