Reputation: 9939
If #box
doesn't have a containing div with a class of current-map
, then do something.
I thought the !
would have worked but it doesn't.
if (!$('#box').closest('.current-map')) {
//do something
}
Upvotes: 2
Views: 66
Reputation: 14747
You should use the :has()
selector instead. Turn the logic around.
if ( $('.current-map:has(#box)').length > 0 ) {
// do backflips
}
.closest()
is sort of notorious for being rather slow to work with.
Upvotes: 1
Reputation: 9680
Try .length in your if block
if ($('#box').closest('.current-map').length > 0) {
//do something
}
Upvotes: 0
Reputation: 165951
You could check the length of the resulting selection. If it's 0
, there was no ancestor .current-map
element:
if($("#box").closest(".current-map").length) {
//.current-map is an ancestor
}
Your attempt does not work because most jQuery methods will return an instance of jQuery whether it contains any DOM elements or not, and that will always evaluate to true
.
Upvotes: 4