Reputation: 3854
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
Reputation: 206078
.mainrow
using .closest()
.nextUntil()
to get the next-siblings.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