jQuery选择最接近元素的子元素

jQuery select child of closest element

本文关键字:元素 最接近 选择 jQuery      更新时间:2023-09-26

基本上我希望能够从子level4div中选择div level2父级。我的应用程序没有这样的类,否则我只选择level2:)

<div class="level1">
  <div class="level2">
    <div class="level3">
      <div class="level4"></div>
    </div>
  </div>
  <div class="level2"> <!-- this is hidden -->
    <div class="level3">
      <div id="start" class="level4"></div>
    </div>
  </div>
</div>

我从$('#start')开始,搜索可见的第一个父级,但我没有看到返回该父级的子级的方法。在父节点中搜索$('#start')似乎非常浪费,因为我从子节点开始。

$('#start').closest(':visible') // returns level1
$('#start').closest(':visible').first() // returns the first level2. I can't just use second because the number of level2s can change.
$('#start').closest(':visible').children().each(function(){ /* do some search to check it contains `$('#start')` }) // seems very wasteful.

另一种理解我想说的话的方式是;从中间开始,找到外部(可见元素),并移动一个元素。

这个怎么样:-

$('#start').parentsUntil(':visible').last();

这将给你所有隐藏的父div,直到它的可见父div和last()将给最外层的父div,它是隐藏的。Last在位置上不是选择器,它是集合中的最后一个()

你想使用。has()方法

Description:将匹配的元素集合减少到那些有一个后代与选择器或DOM元素匹配的元素。

$('#start').closest(':visible').children().has('#start');

你说类不存在…为什么不添加它们呢?这将使思想更容易被发现。类名不需要与实际的样式相关联。

var allLevel4 = $('#start').closest(':visible').find('.level4');
var firstLevel4 = $('#start').closest(':visible').find('.level4')[0];
var secondLevel4 = $('#start').closest(':visible').find('.level4')[1]; //also, #start

使用.filter():

$('#start').closest(':visible').children().filter(':first-child')

.find()也可以很好地选择几乎任何东西。