ReynierPM ReynierPM - 23 days ago 10
HTML Question

How to check if element is empty after the DOM has changed?

I have this code:



$(function() {
$('.delete').click(function() {
$(this).closest('li').remove();
});

$('#items').change(function() {
if ($(this).is(':empty')) {
alert('No more conditions');
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="items">
<li><a href="#" class="delete">Delete me</a></li>
</ul>





As soon as I click on the link, I will get an empty UL but using
.is('empty')
on
.change()
event doesn't trigger the alert.

Is that the correct way to check whether the element is empty or not after the DOM changes? If not what would be the right one?


Note: the solution has to be compatible with older browsers like IE8

Answer

How about this solution. Hope it helps!

$(function() {
  $('.delete').click(function() {
  $(this).closest('li').remove();
  if ($('#items li').length === 0) {
  alert('No more conditions');
  }
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul id="items">
  <li><a href="#" class="delete">Delete me</a></li>
</ul>