简体   繁体   中英

jQuery counting highest number of children in parents

I'd appreciate help on the following problem: Let's say I have a number of ul elements on a page, each with a number of li children, eg

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

What would be the best way to find the highest number of children across all ul parents (In the example above, it should return 3 )?

Many thanks, Ch

You just need this:

var high = Math.max.apply(null, $('ul').map(function () {
    return $(this).children().length;
}).get());
alert(high);

DEMO

You can easily check how many li elements ul containing by checking length

Try FIDDLE

var highest='0';
$('ul').each(function(){
  var elem=$(this).find('li').length; 
  if(elem >= highest)
     highest=elem;
});

alert("Highest no. of li elements is "+highest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM