admin管理员组文章数量:1391975
Here's how the HTML markup looks like
<ul>
<li>red</li>
<li>green</li>
<li>
<ul>
<li>banana</li>
<li>pineapple</li>
<li>peanut</li>
</ul>
</li>
<li>blue</li>
<li>
<ul>
<li>sun</li>
<li>mars</li>
<li>earth</li>
</ul>
</li>
<li>orange</li>
</ul>
how do I count direct children (<li>
) in this list? (items containing red,green,blue,orange) ?
Here's how the HTML markup looks like
<ul>
<li>red</li>
<li>green</li>
<li>
<ul>
<li>banana</li>
<li>pineapple</li>
<li>peanut</li>
</ul>
</li>
<li>blue</li>
<li>
<ul>
<li>sun</li>
<li>mars</li>
<li>earth</li>
</ul>
</li>
<li>orange</li>
</ul>
how do I count direct children (<li>
) in this list? (items containing red,green,blue,orange) ?
-
3
First, before asking this question, correct your HTML. A
ul
is not a valid child of anotherul
element. Wrap the childul
elements inli
elements (which are the only valid children of aul
orol
). – David Thomas Commented May 19, 2012 at 17:48 - 1 possible duplicate of Select all li's but not children -- please use the search before you ask a new question. See also How can I count the number of children?. – Felix Kling Commented May 19, 2012 at 18:11
3 Answers
Reset to default 4Try this:
$('ul > li').length;
'ul > li'
selector point only first level of children i.e direct children for all ul.
or
$('ul').children().length;
If your code is string variable like
var html = '<ul><li>.....';
Then
$('ul > li', $(html)).length;
NOTE: Above code will find all li
To find only first level of li
use:
$('ul:not(li > ul)').children().length;
You can also use:
$('ul:not(li > ul) > li').length
For html variable string:
$(html).children('ul > li').length;
var ul = document.querySelector('ul');
var count = 0;
for (var ch = ul.firstChild; ch; ch = ch.nextSibling)
if (ch instanceof HTMLLIElement) count++;
Use this:
$("ul > li").length
Other way:
$("ul").children().length
In JQuery documentation you can also find size()
method to get the number of elements. However, it is better to use length
, since it is simply faster.
The first ul
element can be taken by :first
selector. Another way is to set the concrete <ul>
element ID, and address it with #element_id
selector.
DEMO: http://jsfiddle/xDYn9/
本文标签: javascriptcount direct children in html listStack Overflow
版权声明:本文标题:javascript - count direct children in html list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744705422a2620813.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论