首页 文章

jQuery计数子元素

提问于
浏览
286
<div id="selected">
  <ul>
    <li>29</li>
    <li>16</li>
    <li>5</li>
    <li>8</li>
    <li>10</li>
    <li>7</li>
  </ul>
</div>

我想计算 <div id="selected"></div><li> 元素的总数 . 怎么可能使用jQuery的 .children([selector])

7 回答

  • 12

    您可以使用.length只使用descendant selector,如下所示:

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

    如果你必须使用.children(),那么它是这样的:

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

    You can test both versions here .

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

    要么:

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

    最快的一个:

    $("div#selected ul li").length
    
  • 17
    var length = $('#selected ul').children('li').length
    // or the same:
    var length = $('#selected ul > li').length
    

    您可能还可以在子项选择器中省略 li .

    .length .

  • 29

    你可以使用JavaScript(不需要jQuery)

    document.querySelectorAll('#selected li').length;
    
  • 10
    $('#selected ul').children().length;
    

    甚至更好

    $('#selected li').length;
    
  • 2

    在纯javascript中只需 childElementCount 即可

    var countItems = document.getElementsByTagName("ul")[0].childElementCount;
    console.log(countItems);
    
    <div id="selected">
      <ul>
        <li>29</li>
        <li>16</li>
        <li>5</li>
        <li>8</li>
        <li>10</li>
        <li>7</li>
      </ul>
    </div>
    

相关问题