Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Find the closest parent having a class name

Tags:

jquery

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.. :-)

like image 780
Sherin Jose Avatar asked Jan 14 '15 12:01

Sherin Jose


People also ask

How do I find my nearest parent by class?

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.

How do I find a specific parent in jQuery?

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.

What is the difference between parent () and parents () methods in jQuery?

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.


2 Answers

To get the first one parent of specific class:

$(this).parents('.selectable').first();
like image 200
A. Wolff Avatar answered Sep 22 '22 13:09

A. Wolff


Then start using closest() on the parent()

$(".selectable").click(function(){
    var closest = $(this).parent().closest('.selectable'); 
});  
like image 22
Amit Joki Avatar answered Sep 24 '22 13:09

Amit Joki