jQuery count child elements

jQuery count child elements

  • 29
  • 16
  • 5
  • 8
  • 10
  • 7

I want to count the total number of

  • elements in

    . How is that possible using jQuery’s .children([selector])?

    Solutions/Answers:

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

    Solution 2:

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

    or:

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

    Solution 3:

    fastest one:

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

    Solution 4:

    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.

    Solution 5:

    You can use JavaScript (don’t need jQuery)

    document.querySelectorAll('#selected li').length;
    

    Solution 6:

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

    or even better

     $('#selected li').length;