Rather than using the jQuery .parents
function (as suggested in the accepted answer), it's better to use .closest
for this purpose. As explained in the jQuery api docs, .closest
checks the element passed and all its parents, whereas .parents
just checks the parents.
Consequently, this works:
$(function() {
$("body").click(function(e) {
if ($(e.target).closest("#myDiv").length) {
alert("Clicked inside #myDiv");
} else {
alert("Clicked outside #myDiv");
}
});
})