Cecil Theodore
Cecil Theodore

Reputation: 9939

If div doesnt have a containing div with a certain class, do something. JQuery

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

Answers (3)

Richard Neil Ilagan
Richard Neil Ilagan

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

Amar Palsapure
Amar Palsapure

Reputation: 9680

Try .length in your if block

   if ($('#box').closest('.current-map').length > 0) {
      //do something
   }

Upvotes: 0

James Allardice
James Allardice

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

Related Questions