jQuery count child elements

gautamlakum picture gautamlakum · Nov 27, 2010 · Viewed 429.9k times · Source

I want to count the total number of <li> elements in <div id="selected"></div>. How is that possible using jQuery's .children([selector])?

Answer

Nick Craver picture Nick Craver · Nov 27, 2010

You can use .length with just a descendant selector, like this:

var count = $("#selected li").length;

If you have to use .children(), then it's like this:

var count = $("#selected ul").children().length;

You can test both versions here.