<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]) ?
<div id="selected"></div>
<li>
.children([selector])
您可以使用.length只使用descendant selector,如下所示:
var count = $("#selected li").length;
如果你必须使用.children(),那么它是这样的:
var count = $("#selected ul").children().length;
You can test both versions here .
$("#selected > ul > li").size()
要么:
$("#selected > ul > li").length
最快的一个:
$("div#selected ul li").length
var length = $('#selected ul').children('li').length // or the same: var length = $('#selected ul > li').length
您可能还可以在子项选择器中省略 li .
li
见.length .
你可以使用JavaScript(不需要jQuery)
document.querySelectorAll('#selected li').length;
$('#selected ul').children().length;
甚至更好
$('#selected li').length;
在纯javascript中只需 childElementCount 即可
childElementCount
var countItems = document.getElementsByTagName("ul")[0].childElementCount; console.log(countItems);
7 回答
您可以使用.length只使用descendant selector,如下所示:
如果你必须使用.children(),那么它是这样的:
You can test both versions here .
要么:
最快的一个:
您可能还可以在子项选择器中省略
li
.见.length .
你可以使用JavaScript(不需要jQuery)
甚至更好
在纯javascript中只需
childElementCount
即可