Reputation: 862
Here I am trying to traverse down and remove the nearest div with class div2
but it is not working properly.
The issue is if I click the random cancel button for e.g click cancel button at last.
$(document).on("click", ".cancel", function () {
$('.div').find('.div2').first().remove();
$(this).closest('.div1').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello2</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello3</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello4</p>
</div>
</div>
Upvotes: 1
Views: 332
Reputation: 10922
You could rather do it this way, remove the div after the parent (the following div2), and then remove the parent (the div1)
$(document).on("click", ".cancel", function() {
let $_parent = $(this).parent();
$_parent.next('div').remove();
$_parent.remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello2</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello3</p>
</div>
<div class="div1">
<button class="cancel" type="button">Cancel</button>
</div>
<div class="div2">
<p>hello4</p>
</div>
</div>
Upvotes: 1