santa santa - 3 months ago 11
HTML Question

How to bind click event to element hasn't specific child using jquery?

I have several elements on a page like bottom code.

<div>
<a href="#" id="notme">click</a>
some content
</div>


They can be clicked and jQuery picks that click. However one of the elements has a
a
link that is clicked should not be picked as a click of the parent element.

$('div:not(#notme)').on('click', function(e) {
// do something
});


Doesn't seem to work for some reason...

Answer

Use :has selector to selecting div element has specific child. In :has use :not.

$("div:has(a:not(#notme))").on("click", function(e) {
    console.log("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <a href="#" id="notme">click</a>
   some content 
</div>
<div>
   <a href="#" >click2</a>
   some content 2
</div>