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.
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")
}