1

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); }); 
1
  • Do you mean child or descendant? Commented Apr 16, 2012 at 13:35

3 Answers 3

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

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

if ($(e.target).closest('#someDiv').length == 0) { 
Sign up to request clarification or add additional context in comments.

3 Comments

.closest() starts with the element itself and stops if it finds something. if by any chance the selector matches the child (like say using a class), it will return itself. .parents() would be safer.
@Joseph Nicely spotted. Then use .parent().closest('#someDiv').
@RobW missed that one. i thought the OP meant to use something .on or .delegate.
1

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.