Friday, May 4, 2012

jQuery count child elements


Here is my HTML code.




<div id="selected">
<ul>
<li>29</li>
<li>16</li>
<li>5</li>
<li>8</li>
<li>10</li>
<li>7</li>
</ul>
</div>



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



Please help.


Source: Tips4all

5 comments:

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

    ReplyDelete
  2. var length = $('#selected ul').children('li').length
    // or the same:
    var length = $('#selected ul > li').length


    You probably could also omit li in the children's selector.

    See .length.

    ReplyDelete
  3. $("#selected > ul > li").size()


    or:

    $("#selected > ul > li").length

    ReplyDelete
  4. $('#selected ul').children().length;


    or even better

    $('#selected li').length;

    ReplyDelete
  5. fastest one:

    $("div#selected ul li").length

    ReplyDelete