JQuery - 查找具有给定数量兄弟的元素

时间:2017-08-14 03:15:54

标签: javascript jquery find

我需要能够搜索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>标记,应该返回。所以它应该返回最低级别元素集合的集合,其兄弟姐妹总计给定量。

2 个答案:

答案 0 :(得分:1)

以下示例从您发布的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>

答案 1 :(得分:0)

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

&#13;
&#13;
const N = 3;

let res = $("> *", $(".search-me > *").toArray().reverse()
          .filter(function(el) {return $("> *", el).length === N}));

console.log(res);

res.css("color", "purple")
&#13;
<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>
&#13;
&#13;
&#13;