[英]How many li there are inside ul with javascript
How can I know how many li
there are inside in the first ul
? 我怎么知道第一个ul
里面有多少li
?
I know I can use .length, but I want just the number of first-ul 我知道我可以使用.length,但是我只需要first-ul的数量
<ul class="first-ul">
<li>1</li>
<li>2</li>
<li>
<ul class="second-ul">
<li>2.1</li>
<li>2.2</li>
</ul>
</li>
</ul>
Use >
to get immediate children li
: 使用>
获取直系孩子li
:
alert(number = $('ul.first-ul > li').length);
http://jsfiddle.net/5oykbysk/1/ http://jsfiddle.net/5oykbysk/1/
See JQUERY DOCS for details 有关详细信息,请参见JQUERY DOCS。
[].filter.call(
document.getElementsByClassName('first-ul')[0].children,
function (el) {
return el.nodeName === 'LI';
}
).length
use jQuery child selector
. 使用jQuery child selector
。 Try this: 尝试这个:
$('ul.first-ul > li').length
it's the best and easy way : 这是最好,最简单的方法:
var x = document.getElementsByClassName(".first-ul").childElementCount;
alert (x);
Visit https://www.w3schools.com/jsref/prop_element_childelementcount.asp 访问https://www.w3schools.com/jsref/prop_element_childelementcount.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.