检查元素是否是给定元素的父元素

Cle*_*lem 1 javascript jquery parent

我如何检查,如果点击的元素不是某个特定DIV元素的子元素?

$("body").click(function(e) {
    if(e NOT child of $('#someDiv')) alert(1);
});
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 6

if ($(e.target).parent('#someDiv').length == 0) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

或者,你是说("不是e的祖先"):

if ($(e.target).closest('#someDiv').length == 0) {
Run Code Online (Sandbox Code Playgroud)

  • @Joseph很好地发现了.然后使用`.parent().nearest('#someDiv')`. (2认同)