Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery count li elements inside ul -> length?

Tags:

jquery

If a ul has more than one li-element inside of it, something should happen, otherwise not!

What am I doing wrong?

if ( $('#menu ul').length > 1 ) {
like image 670
matt Avatar asked Jul 01 '10 14:07

matt


3 Answers

You have to count the li elements not the ul elements:

if ( $('#menu ul li').length > 1 ) {

If you need every UL element containing at least two LI elements, use the filter function:

$('#menu ul').filter(function(){ return $(this).children("li").length > 1 })

You can also use that in your condition:

if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {
like image 132
jantimon Avatar answered Oct 18 '22 14:10

jantimon


The correct syntax is

$('ul#menu li').length
like image 34
Jyoti Raj Avatar answered Oct 18 '22 14:10

Jyoti Raj


alert( "Size: " + $( "li" ).size() );

alert( "Size: " + $( "li" ).length );

Both .size() and .length return number of item. but size() method is deprecated (JQ 1.8). .length property can use for instead of size().

also you can use

alert($("ul").children().length);
like image 12
Umanda Avatar answered Oct 18 '22 16:10

Umanda