views:

1413

answers:

4

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?

+4  A: 

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'.

jacobangel
+2  A: 
var $list = $('#cyclelist li');

alert($list.length);

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

karim79
+2  A: 

Your selector is selecting the dom element with id "cyclelist" which is a single element (the ul with that id). What you would like to do is select the li elements attached to that ul. To do this you can do (as mentioned)

    $('#cyclelist li')
kgrad
+1  A: 
$('#cyclelist')

uses a CSS selector for an element with id="cyclelist" and therefore returns one element/object reference so that's correct ;-)

What I guess you probably meant was

$('#cyclelist li')

to return the list items within the named element.

A more jQuery-esque way to go about iterating over collections of elements is to use each, c.f. http://docs.jquery.com/Core/each

eimaj