Friday, 23 August 2013

Event bubbling up to match the original selector

Event bubbling up to match the original selector

I have a recurring problem with event bubbling with jQuery that I'm
looking for a super simple solution to.
Let's say I have this link:
<a href="http://www.google.com" class="link"><span>Link Text</span></a>
And I bind a click event with jQuery with:
$('.menu a.item').bind('click', function(e){
e.stopPropagation();
e.preventDefault();
var obj = $(e.target);
// do something with obj
});
The problem I consistently face with above and similar bindings is if the
inner HTML of an element has other tags those events become the target.
That's all fine an dandy of course, but I'm wondering if there is a quick
and easy way to parent() up until the parent() obj is equal to the
selector "a.item" so I can grab the href value and do something with it.
In the above case, simple $(e.target).parent().attr('href') would work but
in my case sometimes there are 3 or 4 levels deep of child elements.
Does anyone have any ideas?

No comments:

Post a Comment