How can I count the number of children?

后端 未结 5 1806
北荒
北荒 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 <li> under <ul> elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other <ul> 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;
    
    0 讨论(0)
  • 2020-11-27 05:17

    What if you are using this to determine the current selector to find its children so this holds: <ol> then there is <li>s under how to write a selector var count = $(this+"> li").length; wont work..

    0 讨论(0)
  • 2020-11-27 05:18

    Try to get using:

    var count = $("ul > li").size();
    alert(count);
    
    0 讨论(0)
  • 2020-11-27 05:27

    You don't need jQuery for this. You can use JavaScript's .childNodes.length.

    Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

    var count = elem.childNodes.length - 1;
    
    0 讨论(0)
  • 2020-11-27 05:35

    You can do this using jQuery:

    This method gets a list of its children then counts the length of that list, as simple as that.

    $("ul").find("*").length;
    

    The find() method traverses DOM downwards along descendants, all the way down to the last descendant.

    Note: children() method traverses a single level down the DOM tree.

    0 讨论(0)
提交回复
热议问题