Reputation: 2526
In my application i want to find the closest parent, of a clicked element, having a class name. For that i have the following code with closest method. I know it has the functionality to get the closest element with a selector. But here i given a class name as selector like;
$(".selectable").click(function(){
var closest = $(this).closest('.selectable');
});
The problem is if the current element and its parent have the same class .selectable
, it returns the current element itself. But actually i want its parent. For example,
<div class="selectable div-1">
<div class="selectable div-2">
<!--elements here-->
</div>
</div>
In the above example i clicked on .div-2
div, it returns the .div-2
itself, not the .div-1
div. Please dont ask me to remove .selectable
class from the parent, it's for the functionality.. :-)
Upvotes: 7
Views: 20130
Reputation: 82241
You need to use .parents()
instead of .closest()
:
$(this).parents('.selectable');
.closest()
looks at all ancestors, as well as the originating element, and returns the first match.
.parents()
looks at all ancestors, and returns all matches.
Upvotes: 3
Reputation: 2869
Also remember to return false
in your method in order to avoid bubbling:
$(".selectable").click(function() {
// var closest = $(this).parent().closest('.selectable');
var selectableParentExist = $(this).parents('.selectable').length;
if (selectableParentExist > 0) {
var closest = $(this).parents('.selectable');
alert(closest.attr("id"));
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="parentDiv" class="selectable div-1">Parent Div
<div id="selectableDiv" class="selectable div-2">
<!--elements here-->Selectable Div
</div>
</div>
Upvotes: 0
Reputation: 74420
To get the first one parent of specific class:
$(this).parents('.selectable').first();
Upvotes: 17
Reputation: 28513
You can use parents
like below -
$(".selectable").click(function(){
var closest = $(this).parents('.selectable');
});
Upvotes: 2
Reputation: 59232
Then start using closest()
on the parent()
$(".selectable").click(function(){
var closest = $(this).parent().closest('.selectable');
});
Upvotes: 6