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/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744705423a4589026.html
评论列表(0条)