简体   繁体   中英

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

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; 

Or try

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

which returns 4 in your case

You could try one of these:

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

您应该给第一个ul提供一个ID或类,然后您可以使用like

alert($(".classname").children("li").length);

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; var x = $('#myId').children('li'); count = x.length;

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

Gives you a result of 4.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM