简体   繁体   English

jQuery在特定级别选择子元素

[英]jquery selecting child elements on specific level

i have a DOM something like 我有一个类似的DOM

<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 我如何才能仅获得第一级李计数,但子ul元素具有的所有li元素的总和

Try > child-selector or .children() 尝试> child-selector.children()

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

$('ul > li:not(:has(ul))').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 为此,更好的选择作者: Arun P Johny爵士

Fiddle Demo 小提琴演示

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

Or try 或尝试

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

which returns 4 in your case 在您的情况下返回4

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/ https://api.jquery.com/children/

jquery .children() returns the immediate children of whatever element jquery .children()返回任何元素的直接子代

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. 因此,要么将父ul存储在变量中(如果这是动态应用程序,或者在该元素上执行大量js,就应该这样做),或者需要在该ul上放置一个ID。 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; var x = $('#myId').children('li'); count = x.length;

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

Gives you a result of 4. 给你结果4。

You can try it here - http://jsfiddle.net/rQWb3/ 您可以在这里尝试-http://jsfiddle.net/rQWb3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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