aw crud
aw crud

Reputation: 8891

How can I select elements living in a certain range of the DOM hierarchy?

I have a DOM element C which is a descendant of DOM element A. There are several layers between them, one of which is an class of element named B.

If I have jQuery("#A") and jQuery("#C), how can I find the parent element of C with class B, which is also a descendant of A?

If I use parents() of C then I could potentially get any elements with class B which are above A, which I do not want. If I use find() of A then I could get elements below C, which I do not want.

The number of layers between each of the elements I am interested in is not known. While the example shows a single layer, which would allow me to do .children().children(), I can't be certain that it's only 2 levels away.

e.g.

...
<div id="A">
 <div>
   <div class="B">
     <div>
       <div id="C">...</div>
     </div>
   </div>
 </div>
</div>

Upvotes: 0

Views: 71

Answers (2)

David Hellsing
David Hellsing

Reputation: 108482

$('#C').closest('.B').filter(function() {
    return $(this).closest('#A').length;
});

You dont need the filter if you know that the closest div.B will always be below #A

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

in this situation, you need .closest()

$('#C').closest('.B') // would get the closest parent(.B) of a child(#C)

Upvotes: 1

Related Questions