136

I've got a list that is generated from some server side code, before adding extra stuff to it with jQuery I need to figure out how many items are already in it.

<ul id="mylist">
    <li>Element 1</li>
    <li>Element 2</li>
</ul>
Tom
  • 33,626
  • 31
  • 85
  • 109

9 Answers9

228

Try:

$("#mylist li").length

Just curious: why do you need to know the size? Can't you just use:

$("#mylist").append("<li>New list item</li>");

?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 3
    I'm using appending to add the new ones, but I've got a limit on the number of items that can be in the list, in this state the user can still add upto a max of 4 items, but 2 might have come from the previous state. :) – Tom Mar 03 '09 at 11:18
  • 35
    Note that the jQyery docs recommend using `.length` over `.size()` to avoid the overhead of a function call. http://api.jquery.com/size/ – Joe Dec 01 '11 at 23:18
  • 4
    [size() was deprecated in jquery 1.8](http://api.jquery.com/size/) and it says to use [length()](http://api.jquery.com/length/) now. – gloomy.penguin Apr 06 '13 at 20:48
  • 8
    @gloomy.penguin Note that `.length` is not a function. – hexacyanide Apr 23 '13 at 22:28
  • I need the
  • count in order to recalculate the element width on the fly.
  • – Hristo Jul 26 '15 at 22:52