Clem
Clem

Reputation: 11824

Check whether an element is a parent of a given element

how can i check, if clicked element is not child of some specific DIV element?

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

Upvotes: 1

Views: 212

Answers (3)

Joseph
Joseph

Reputation: 119847

$('yourElement').on('click',function(){
      if(!$(this).parents('theDiv').length){
          //not a child
      }
});

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

You can use the parent method with a selector to return the parent element if it matches that selector. You can then check the length property to see if the parent element was returned:

$("body").click(function(e) {
    if(!$(this).parent("#someDiv").length) {
        alert("Not a child");
    }
});

If you want to check whether the clicked element is not an ancestor, you can use parents instead of parent.

Upvotes: 1

Rob W
Rob W

Reputation: 349012

if ($(e.target).parent('#someDiv').length == 0) {
    ...
}

Or, did you mean ("not an ancestor of e"):

if ($(e.target).closest('#someDiv').length == 0) {

Upvotes: 6

Related Questions