Graham Walters
Graham Walters

Reputation: 2064

jQuery select child of closest element

Basically I want to be able to select the div level2 parent from the child level4 div. My application does not has such classes, otherwise I'd just select 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. Searching for $('#start') inside the parent seems very wasteful as I start with a sub child to begin with.

$('#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.

Upvotes: 2

Views: 7986

Answers (4)

user428517
user428517

Reputation: 4193

Use .filter():

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

.find() is also good for selecting pretty much anything.

Upvotes: 0

km6zla
km6zla

Reputation: 4877

You want the .has() method

Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

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

See fiddle for example.

Upvotes: 3

PSL
PSL

Reputation: 123739

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. last is not a selector on position it is the last() in the collection.

Upvotes: 3

Ryan Rahlf
Ryan Rahlf

Reputation: 1802

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

Upvotes: 0

Related Questions