1

I would like to determine when the <ul> tag is empty after removing <li> tags. Can someone help me?

There is a html code:

$(document).on('click', '.close', function(e) {
  $(this).parent().fadeOut("normal", function() {
    $target.remove();
  });
  if ($(this).closest(".indexy").not(".info")) {
    alert("prazdne");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="indexy">
  <li class="info">ASD<button type="button" class="close">&times;</button></li>
  <li class="info">FGH<button type="button" class="close">&times;</button></li>
  <li class="info">JKL<button type="button" class="close">&times;</button></li>
</ul>

5 Answers5

2

Use the length property when using the selector you want to check.

if($('ul.indexy li').length < 1){
    console.log('empty');
}
malux
  • 63
  • 4
2
$(document).on('click', '.close', function(e) {
  $(this).closest("li").remove();
  if (!$(".indexy").find('li').length) {
    alert("UL is empty")
  }
});

Fiddle Demo

Rino Raj
  • 6,264
  • 2
  • 27
  • 42
1

I think you can't use $(this) because you already removed it from DOM . it's no more in DOM

$(document).on('click', '.close', function(e) {

       $(this).parent('li').remove();
                   
       if($('.indexy li').length<1){
                
           console.log('ul empty ');
        }else{
        
           console.log('li length is :'+$('.indexy li').length);
        }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="indexy">
            <li class="info">ASD<button type="button" class="close">&times;</button></li>
            <li class="info">FGH<button type="button" class="close">&times;</button></li>
            <li class="info">JKL<button type="button" class="close">&times;</button></li>
        </ul>
JYoThI
  • 11,977
  • 1
  • 11
  • 26
1

You can do something like this for your js code:

function removeListItem(item) {  
  $('#'+item).fadeOut("normal", function(){
    $(this).remove();
    var li = $('li.info');
    alert(li.length);
    if (li.length <= 0){
        alert("prazdne");
    }        
  })
}

I've changed your HTML a bit too. This is a li for example:

<li id="element1" class="info">ASD<button type="button" class="close" onclick="removeListItem('element1')">&times;</button></li>

One thing you weren't doing was actually remove the list items from the DOM.

0

You can do this with js var confirm = document.getElementsByClassName("indexy")[0].hasChildNodes(); If it has childNodes or children it will return "true" to the variable confirm, if not it will return "false". The index for the list is zero if that is the only element with that class name. Otherwise you would have to iterate

UncleT
  • 77
  • 1
  • 9