Jochen
Jochen

Reputation: 1776

JQuery - grab parent of event-object

I bound a function as a closure to an anchor like this:

jQuery('#mydiv').find('#mya').bind('click', function(e){
    myotherfunction(e);
});

In my function myotherfunction(obj), obj is an event, how do I get the parent-Element?

Upvotes: 2

Views: 1200

Answers (1)

gdoron
gdoron

Reputation: 150253

With this:

jQuery(obj.target).parent();

You might want to refactor your code to this:

jQuery('#mya').bind('click', function(e){
    myotherfunction(e.target);
});

function myotherfunction(obj){
    var $parent = jQuery(obj).parent();
    ...
    ...
}

Best practices:

  • obj is a bad name for the event variable.
  • id should be unique so you can search by it only:
    jQuery('#mydiv').find('#mya') => jQuery('#mya')

Upvotes: 8

Related Questions