Javascript jQuery 计数子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4291151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:46:12  来源:igfitidea点击:

jQuery count child elements

javascriptjquerydom

提问by gautamlakum

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

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

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

回答by Nick Craver

You can use .lengthwith just a descendant selector, like this:

您可以.length仅使用后代选择器,如下所示:

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

If you have to use .children(), then it's like this:

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

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

You can test both versions here.

您可以在此处测试这两个版本

回答by bcosca

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

or:

或者:

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

回答by Ali Tarhini

fastest one:

最快的一个:

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

回答by Felix Kling

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

You probably could also omit liin the children's selector.

您可能也可以li在孩子的选择器中省略。

See .length.

.length

回答by ??ng V?n Thanh

You can use JavaScript (don't need jQuery)

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

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

回答by Martin Algesten

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

or even better

甚至更好

 $('#selected li').length;

回答by Mo.

It is simply possible with childElementCountin pure javascript

childElementCount在纯javascript中很可能

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>

回答by Kamil Kie?czewski

pure js

纯js

selected.children[0].children.length;

let num = selected.children[0].children.length;

console.log(num);
<div id="selected">
  <ul>
    <li>29</li>
    <li>16</li>
    <li>5</li>
    <li>8</li>
    <li>10</li>
    <li>7</li>
  </ul>
</div>