user1937021
user1937021

Reputation: 10781

how to check if all items in list are empty

Say I have a list as follows, content within the <li>s is loaded in dynamically. Is there a way to check if all items in the list are empty with JQuery?

<ul class="clearfix">
   <li data-product-pid="50267857_420" class="productTile">
   </li>
   <li data-product-pid="50265598_100" class="productTile">
   </li>
   <li data-product-pid="50267794_821" class="productTile">
   </li>
   <li data-product-pid="50268227_821" class="productTile">
   </li>
</ul>

Upvotes: 0

Views: 2178

Answers (6)

Devima
Devima

Reputation: 1566

Probably this was not required but with this solution you can see if all li tags are empty or know which of these tags has the text.

<script type="text/javascript">
$(document).ready(function(){
    var len=$('li').length,arr=[]
    for(i=0;i<len;i++){
        var tx= $('li:eq('+i+')').text().length
        if(tx===0){arr.push('e')}else{console.log('Li element nuber '+(i+1)+ ' contains text')}
    }
    if(arr.length===len){console.log('all li are empty')}
})
</script>

Upvotes: 0

Onur Topal
Onur Topal

Reputation: 3061

With new JS standart you have Array.every but I am pretty sure you cannot use it so you have to do with classic loop way. below is a simple way of doing is it would be more handy if you can convert it to jQuery plugin.

function isAllEmpty (yourArr) {
   var isAllEmpty = true;
   $.each(yourArr, function () {
      if ($(this).text() !== '') {
         isAllEmpty = false;
         return false; //breaks loop;
      }
   });

   return isAllEmpty
}

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use empty-selector,

if($('ul li.productTile').length == $('ul li.productTile:empty').length)    {
    alert('all li are empty')
}

Live Demo

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

$('.productTile').each(function(){
   if($(this).text() == ""){
    //do stuff here if empty
  } else {
   // do stuff here if not empty
  }
});

Upvotes: 0

nuss
nuss

Reputation: 1320

var isEmpty = false;
$(ul li).each(function() {
    if($(this).html() == "") {
          isEmpty = true;
    }
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

Try this:

if($('ul li').length==$('ul li').filter(function() {return $(this).text()​​​​​​​ == '';}).length)    {
  //all are empty
}

Upvotes: 0

Related Questions