views:

15

answers:

2

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>
+1  A: 

in this situation, you need .closest()

$('#C').closest('.B') // would get the closest parent(.B) of a child(#C)
Reigel
@Reigel: Awesome.
RenderIn
+1  A: 
$('#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

David