Tim Marshall Tim Marshall - 1 year ago 82
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

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
an despite my searches, I cannot resolve to as why you cannot click the
within the
because you're still clicking on the link, aren't you/...

Here is a JSFiddle example of my problem

Answer Source

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
   // do something else when not <a>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download