Usually when I want to check if any child element inside a parent element was clicked I use something like this:
$(document).click(function (e) {
alert($(e.target).is("#somediv *"));
}
But now I have the somediv in a variable. I have tried:
var somediv = $(this);
$(document).click(function (e) {
alert($(e.target).is($(somediv, "*")));
}
But it doesn’t work. How can I do that? Is it the best way to detect if a element or any child element was clicked?
No matter whether
somedivis a DOM element or a selector, use.closest[docs]:This will traverse the DOM up, starting at
e.targetand tests whether any ancestor (or the element itself) issomediv. If you want to excludee.target, start at its parent:Another way, depending on the overall context, could be to simply bind the event handler to
somediv:There is no easy way to create a selector from an existing DOM element. If
somedivwas containing a selector then you could use string concatenation to combine it: