Aykut Ateş
Aykut Ateş

Reputation: 184

jquery selecting child elements on specific level

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

Answers (6)

DanG
DanG

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

Try > child-selector or .children()

<ul id="FirstUL">
$('#FirstUL > li').length;

$('ul > li:not(:has(ul))').length;


.parents()

Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

Fiddle Demo

var len = $('ul > li').filter(function(){
    return $(this).parents('ul').length == 1;
}).length;


Better Coed for that By Sir Arun P Johny

Fiddle Demo

$('li:not(ul ul li)').length;

Upvotes: 2

Original10
Original10

Reputation: 572

 $('ul:first').children('li').length

Gives you a result of 4.

You can try it here - http://jsfiddle.net/rQWb3/

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

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

DarkAjax
DarkAjax

Reputation: 16223

You could try one of these:

$('ul:first > li').length;
$('ul:eq(0)').children('li').length;

Upvotes: 0

Rey Libutan
Rey Libutan

Reputation: 5314

Or try

$("#ulID").children().length

which returns 4 in your case

Upvotes: 0

Related Questions