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?
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'.
var $list = $('#cyclelist li');
alert($list.length);
Put simply: you were getting the number of ULs matching that selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With