If element does not have parent with specific class

Tom picture Tom · Mar 28, 2013 · Viewed 34.9k times · Source

I am trying to create an if statement in jQuery for elements that have a parent with a specific class.

This is what I've come up with so far but it's not right.

if(!$(".myElem").parents(".myDiv")) {
    console.log("test")
};

Can anyone point me in the right direction please.

Answer

adeneo picture adeneo · Mar 28, 2013

Use length to check it there are elements in the selector, and closest() would be better than parents() as it stops once it finds a match:

if(! $(".myElem").closest(".myDiv").length ) {
    console.log("has no parent with the class .myDiv")
}