Reputation: 68494
The HTML looks something like this:
<li class="divider">
<div>
...(maybe more divs)...
<div class="content">
...(maybe more divs)...
<a href="#" class="link">LINK</a>
...
how can I select the .content DIV, from within a jQuery function hooked on the link? Note that I have multiple lists like this, and in some of them div.content might be missing, so I want to select this div only if it exists in the current block (li.divider).
I tried with $link.parent().parent().find('content')
but it fails in some cases, because the number of elements between these 2 elements can change...
Upvotes: 4
Views: 11965
Reputation: 322492
If they're not nested, you should be able to do this:
$('a.link').click(function() {
$(this).closest('div.content');
});
or
$('a.link').click(function() {
$(this).parents('div.content:first');
});
If they are nested, then you may need to do something like this:
$('a.link').click(function() {
$(this).closest('li.divider').find('div.content');
});
...so that if there's nesting going on, and there's no div.content
in the current one, you won't end up selecting a more distant div.content
ancestor.
Upvotes: 7
Reputation: 82483
Use the closest
selector...
var parentContent = $(this).closest("div.content");
if(parentContent.length > 0) {
alert("DIV was found!");
}
Upvotes: 0