Find parent in jQuery event

I added the 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 I do that?

+7
source share
4 answers

Here . parent () is an object traversal method.

according to the Pointy crystal ball, you probably want to do something like this:

 $(document).click(function(event) { if ($(event.target).parents('.selector').length > 0) { } }); 

I'm not sure why you are installing a click handler on a document, maybe you are looking for event delegation and . on () ?

+14
source
 $(document).click(function(event){ var $parent = $(this).parent(); // test parent examples if($parent.hasClass('someclass')) { // do something } if($parent.prop('id') == 'someid')) { // do something } // or checking if this is a decendant of any parent var $closest = $(this).closest('someclass'); if($closest.length > 0 ) { // do something } $closest = $(this).closest('#someid'); if($closest.length > 0 ) { // do something } }); 
+2
source

I have reliably used this in the past:

 var target = $( event.target ) 

This will give you a jQuery object reference for the element that raised the event. You can use the same approach and see if the parent "#parent" is something like this:

 var target = $( event.target ) if (target.parent().attr('id') == "#parent") { //do something } 
+2
source

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

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

Note: sometimes using "I" as a variable is bad / causes conflicts with certain libraries, so I used $ eelf. $ In $ elf is not as special as a jQuery convention or anything else.

+2
source

All Articles