Reputation: 184
i have a DOM something like
<ul>
<li> list item </li>
<li> list item </li>
<li> has sub element
<ul>
<li> list item </li>
<li> list item </li>
<li> list item </li>
<li> has sub element
<ul>
<li> list item </li>
<li> list item </li>
<li> list item </li>
</ul>
</li>
</ul>
</li>
<li> list item </li>
</ul>
how can i get only first level li count except sum of all li elements which child ul elements have
Upvotes: 0
Views: 214
Reputation: 91
Please upvote if this helps you :)
https://api.jquery.com/children/
jquery .children()
returns the immediate children of whatever element
So either you have the parent ul stored in a variable (which you should if this is a dynamic app, or if you're doing a lot of js on that element), OR you need to put an ID on that ul. Then you simply use:
$('#myId').children('li');
That gives you an array of four li's.
From there you can either get the length directly like so:
$('#myId').children('li').length;
or var x = $('#myId').children('li');
count = x.length;
Upvotes: 0
Reputation: 57105
Try > child-selector or .children()
<ul id="FirstUL">
$('#FirstUL > li').length;
$('ul > li:not(:has(ul))').length;
Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
var len = $('ul > li').filter(function(){
return $(this).parents('ul').length == 1;
}).length;
$('li:not(ul ul li)').length;
Upvotes: 2
Reputation: 572
$('ul:first').children('li').length
Gives you a result of 4.
You can try it here - http://jsfiddle.net/rQWb3/
Upvotes: 0
Reputation: 25537
you should give an id or class to the first ul, then you can use like
alert($(".classname").children("li").length);
Upvotes: 0
Reputation: 16223
You could try one of these:
$('ul:first > li').length;
$('ul:eq(0)').children('li').length;
Upvotes: 0
Reputation: 5314
Or try
$("#ulID").children().length
which returns 4 in your case
Upvotes: 0