If element does not have parent with specific class
if($(".myElem").parent().hasClass(".myDiv")) {
console.log("has a parent with the class .myDiv")
}
else
{
console.log("no parent class .myDiv found")
}
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")
}
If you are testing whether the element with class myElem
has a direct parent with class myDiv use the following test
if(!$(".myElem").parent().hasClass("myDiv")) {
console.log("test")
};