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.. :-)
Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.
jQuery parent() Method The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree.
parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.
To get the first one parent of specific class:
$(this).parents('.selectable').first();
Then start using closest()
on the parent()
$(".selectable").click(function(){
var closest = $(this).parent().closest('.selectable');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With