How can I count the number of children?

后端 未结 5 1978
北荒
北荒 2020-11-27 04:57

I have a list

  • ...

I need jQuery to count the number of items in my list.

5条回答
  •  星月不相逢
    2020-11-27 05:13

    You can use .length, like this:

    var count = $("ul li").length;
    

    .length tells how many matches the selector found, so this counts how many

  • under
      elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other
        elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li".

        In other situations where you don't know the child type, you can use the * (wildcard) selector, or .children(), like this:

        var count = $(".parentSelector > *").length;
        

        or:

        var count = $(".parentSelector").children().length;
        

提交回复
热议问题