jQuery: Count number of list elements?

Tom picture Tom · Mar 3, 2009 · Viewed 230.4k times · Source

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>

Answer

cletus picture cletus · Mar 3, 2009

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>");

?