简体   繁体   English

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

[英]jQuery select child of closest element

Basically I want to be able to select the div level2 parent from the child level4 div. 基本上,我希望能够从子级别4的div中选择父级别的div。 My application does not has such classes, otherwise I'd just select 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>

I start with $('#start') and search for the first parent which is visible, but I'm not seeing a way to return the child of that parent. 我从$('#start') ,搜索可见的第一个父级,但是我没有找到一种方法来返回该父级的子级。 Searching for $('#start') inside the parent seems very wasteful as I start with a sub child to begin with. 从父级开始,在父级中搜索$('#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.

Another way to look at what I'm trying to say would be; 看我想说的另一种方式是: start in the middle, find the outside (the visible element), and move one element in. 从中间开始,找到外部(可见元素),然后向内移动一个元素。

How about this:- 这个怎么样:-

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

This will give you all hidden parent div's until its visible parent and last() wil give the outermost parent which is hidden. 这将为您提供所有隐藏的父div,直到其可见的parent和last()将给出被隐藏的最外面的父。 last is not a selector on position it is the last() in the collection. last不是位置上的选择器,它是集合中的last()。

You want the .has() method 您需要.has()方法

Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. 说明:将匹配元素集减少为具有与选择器或DOM元素匹配的后代的元素。

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

See fiddle for example. 例如参见小提琴。

Use .filter() : 使用.filter()

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

.find() is also good for selecting pretty much anything. .find()也非常适合选择几乎所有内容。

You say that the classes don't exist...why not add them? 您说这些类不存在...为什么不添加它们? It would make thinks much easier to find. 这将使思想更容易找到。 The class names don't need to have actual styles associated. 类名不需要关联实际的样式。

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

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

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