Jquery - Count how many UL, have so many LI elements

3

$(function(){

	var count = '';
	var total = 1;
    
	$('ul li').each(function(index, el) {
			count++;
			if(count == 12) {
				total + 1;
			}
      
			count = '';
		});
    
    console.log('Se encontraron 2 UL con 2 li');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  <li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

I have UL and I need to know of all the existing UL, how many UL have 2 LI, what I'm trying to do with each one, this will be the right way.

2 UL were found with 2 li

I would greatly appreciate your help.

    
asked by Learning and sharing 31.03.2017 в 05:58
source

2 answers

6

Ok with each , Here I take the 2 as a fixed value, it can be changed if you want to search ul that contains a certain number of li

$(function(){
   var count=0;
   $('ul').each(function(i) {
	  let len = $(this).find('li').size();
	  if(len==2) count++;
    });
  console.log("SE ENCONTRARON " + count + " CON DOS LI");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>
<ul>
	<li>Item</li>
</ul>
<ul>
	<li>Item</li>
	<li>Item</li>
</ul>
<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  	<li>Item</li>
</ul>
<ul>
	<li>Item</li>
	<li>Item</li>
</ul>
    
answered by 31.03.2017 / 06:11
source
3

To find how many UL there are you only need to do $ ("ul") and to find all LI you apply something similar: $ ("li")

Here is an example.

var a = $("ul");
var b = $("li");

console.log("Se encontraron: "+a.size()+" UL y "+b.size()+" li");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  <li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

Now to be able to access each UL we will do the following

var total = 0;
$.each($("ul"), function (i,v){
if($("li",v).size() == 2){ total +=1}
});
console.log("Se encontraron "+total+" UL con 2 LI");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  <li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>
    
answered by 31.03.2017 в 06:10