Determine empty <ul> tag after removing <li> tag

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>

Upvotes: 1

Views: 1048

Answers (5)

UncleT
UncleT

Reputation: 77

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

Upvotes: 0

Rino Raj
Rino Raj

Reputation: 6264

$(document).on('click', '.close', function(e) {
  $(this).closest("li").remove();
  if (!$(".indexy").find('li').length) {
    alert("UL is empty")
  }
});

Fiddle Demo

Upvotes: 2

Martin Palmieri
Martin Palmieri

Reputation: 116

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.

Upvotes: 1

JYoThI
JYoThI

Reputation: 12085

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>

Upvotes: 1

malux
malux

Reputation: 63

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

if($('ul.indexy li').length < 1){
    console.log('empty');
}

Upvotes: 2

Related Questions