Home > Software engineering >  jquery document on click with ":not" not working
jquery document on click with ":not" not working

Time:03-30

I am sorry if the title is terrible, I was really trying to figure out how to word this lol

What I am trying to do is I have links that a user will click on, within the <a> I have a class called not_me when the user clicks on that I don't want to fire the event. I tried to use :not(.not_me) but the click event is still firing. What am I missing?

jQuery

jQuery(document).on("click",".co_link:not(.not_me)", function() {

})

HTML

<a ><span>Here is some other stuff </span><span >Click Me</span></a>

CodePudding user response:

The event target of the .not_me element does not match the .co_link selector. You're actually targeting an element like: <a >.

You will need to stop propagation on the .not_me element first:

$(document).on('click', '.not_me', (e) => { e.stopImmediatePropagation(); });
$(document).on('click', '.co_link', (e) => { alert('clicked'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a ><span>Here is some other stuff </span><span >Click Me</span></a>

  • Related