Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the <li>s in a <ul> with jQuery

Tags:

jquery

list

I have a simple list like this:

<ul id="cyclelist">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>

and I am using jQuery to cycle through the list. The first problem is finding if the list has more than one elements to start with. I expect something like this to work:

var $list = $('#cyclelist');

if ($list.length > 1) {
  ...
}

But length always returns 1. Is there a better way to find the length of the list using jQuery? Or am I getting this wrong?

like image 311
Morgul Master Avatar asked Dec 03 '22 07:12

Morgul Master


2 Answers

Try $('#cyclelist li').length

The problem is that $('#cyclelist') only has one element--the unordered list as a whole. If you want to know the number of list items in your unordered list, you can just add the additional selector 'li'.

like image 146
jacobangel Avatar answered Dec 21 '22 22:12

jacobangel


var $list = $('#cyclelist li');

alert($list.length);

Put simply: you were getting the number of ULs matching that selector.

like image 34
karim79 Avatar answered Dec 22 '22 00:12

karim79