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
jQuery count child elements
提问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 .length
with just a descendant selector, like this:
var count = $("#selected li").length;
If you have to use .children()
, then it's like this:
如果你必须使用.children()
,那么它是这样的:
var count = $("#selected ul").children().length;
回答by bcosca
$("#selected > ul > li").size()
or:
或者:
$("#selected > ul > li").length
回答by Ali Tarhini
fastest one:
最快的一个:
$("div#selected ul li").length
回答by Felix Kling
回答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 childElementCount
in 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>