繁体   English   中英

jQuery-查找具有给定数量的同级元素

[英]JQuery - Find element that has a given number of siblings

我需要能够搜索JQuery对象的每个后代,并返回在该层次结构级别上可能具有给定数目的成员的所有同级兄弟的集合,从最远的后代对象开始,然后进行备份。

因此,给出一些HTML:

<div class="search-me">
  <div> <!-- DON'T FIND THIS -->
    <p>FIND ME</p>
    <p>FIND ME</p>
    <p>FIND ME</p>
  </div>
  <div> <!-- DON'T FIND THIS -->
    <span></span>
    <span></span>
  </div>
  <div> <!-- DON'T FIND THIS -->
    <div>FIND ME</div>
    <div>FIND ME</div>
    <div>FIND ME</div>
  </div>
</div>

我需要以下伪代码,以返回标有“查找我”的项目,而无其他...

$('.search-me').findGroupWithSize(3);

另外,请注意,有三个div包含<p><span><div>标记,不应其返回。 因此,它应返回一组最低级别的元素的集合,这些元素的同级元素总数为给定的数量。

下面的示例从您发布的HTML中查找3组。

 var siblingsGroupTarget = 3; var foundIndex = 0; var elementArray = []; $(".search-me").find("*").each(function(index){ // Conditions var hasChilds = $(this).children().length; var hasSiblings = $(this).siblings().length; var itsSiblings = $(this).siblings(); var itsSiblingsHasChilds = itsSiblings.children().length; console.log( $(this)[0].tagName+": "+$(this).siblings().length ); if( hasChilds == 0 && ( hasSiblings == siblingsGroupTarget-1 && itsSiblingsHasChilds == 0 ) ){ elementArray.push( $(this) ); } }); elementArray.reverse(); for(i=0;i<elementArray.length;i++){ foundIndex++; elementArray[i].addClass("FOUND").append(" I was found #"+foundIndex); }; 
 .FOUND{ border:3px solid red; width:12em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="search-me"> <div> <!-- DON'T FIND THIS --> <p>FIND ME</p> <p>FIND ME</p> <p>FIND ME</p> </div> <div> <!-- DON'T FIND THIS --> <span></span> <span></span> </div> <div> <!-- DON'T FIND THIS --> <div>FIND ME</div> <div>FIND ME</div> <div>FIND ME <ul> <!-- DON'T FIND THIS --> <li>FIND ME</li> <li>FIND ME</li> <li>FIND ME</li> </ul> </div> </div> </div> 

您可以使用传递给jQuery()选择器".search-me > *"来获取.search-me元素的直接后代,使用.toArray()将jQuery对象转换为数组,使用Array.prototype.reverse()来反转集合的元素, .filter()检查子元素.length是否为N ,用选择器"> *"jQuery()数组方法包装起来,以返回匹配元素的子元素

 const N = 3; let res = $("> *", $(".search-me > *").toArray().reverse() .filter(function(el) {return $("> *", el).length === N})); console.log(res); res.css("color", "purple") 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="search-me"> <div> <!-- DON'T FIND THIS --> <p>FIND ME</p> <p>FIND ME</p> <p>FIND ME</p> </div> <div> <!-- DON'T FIND THIS --> <span>DON'T FIND ME</span> <span>DON'T FIND ME</span> </div> <div> <!-- DON'T FIND THIS --> <div>FIND ME</div> <div>FIND ME</div> <div>FIND ME</div> </div> </div> 

暂无
暂无

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

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