Lao Lao - 4 months ago 10
jQuery Question

How to check if the click was directly in an element or some of its children only?

I don't want clicks on children other than some, and the parent div itself to trigger any events.

Please see this, which does not do what I want:

https://jsfiddle.net/k12e8rgt/3/

$(document).ready(function() {

$('#parent').on('click', function(event) {
alert("you clicked directly on me!");
});

});

Answer

you can use event.target

Example :

$(document).ready(function() {
  $("div").on("click", function(event) {
    alert("You click on : " + event.target.tagName)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>this is Div
  <p>This is p</p>
</div>