Tim Marshall Tim Marshall - 6 months ago 12
jQuery Question

$(e.target) equals a link even if clicking on element within?

I feel I should be more experienced then this however I just cannot seem to resolve. Upon clicking on the link or anything within, I want this to be the

$(e.target)
to call the parent or whatnot.

A breakdown of my script looks like the following;

$(document).on('mousedown', function(e) {
if ($(e.target).is('ul.SiteNav>li>a')) {
alert('Hello World!')
}
});


Of course this is just a snippet but nevertheless, I'm new to using
$(e.target)
an despite my searches, I cannot resolve to as why you cannot click the
<i></i>
within the
<a></a>
because you're still clicking on the link, aren't you/...

Here is a JSFiddle example of my problem

Answer

target will be whatever deepest level element you actually interact with but what is likely confusing you is that events bubble up the dom tree so if an event handler was listening to <a> click, clicking on a child will still bubble to the parent and trigger the event handler

Use closest() to do what you want

if ($(e.target).closest('.SiteNav a').length){
   // code if <a> expected
}else{
   // do something else when not <a>
 }

closest() will also include the actual target and work it's way up from that start point.

Comments