Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find parent element in JQuery event

I've added a click event as follows and would like to check if the target has a specific parent.

$(document).click(function(event){
    // Check here if target has specific parent for example -> #parent
});

How can this be done?

like image 673
ihkawiss Avatar asked Aug 30 '12 15:08

ihkawiss


People also ask

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

Which jQuery method returns the direct parent element of the selected element?

jQuery parent() Method The parent() method returns the direct parent element of the selected element.


1 Answers

I believe this also works.. AFAIK jQuery events use the the literal element instead of a jQuery object when calling events. Basically this should be your normal DOM element with normal JavaScript properties.

$(document).click(function(event)
{
   let myparent = $(this.parentNode); //jquery obj
   let parent = $(this.parentNode)[0]; //plain DOM obj

   let myself = $(this); //jquery obj;
   let $elf = this; //plain DOM obj
});

Note: sometimes using 'self' as a variable is bad/causes conflicts with certain libraries so i used $elf. The $ in $elf is not special; not a jQuery convention or anything like that.

like image 188
Garet Claborn Avatar answered Oct 03 '22 18:10

Garet Claborn