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 the parentElement property to select the parent of the element. Use the classList. contains() method to check if the parent contains the class. The method returns true if the element's class list contains the class and false otherwise.
Let's be clear here, just in case someone is finding this from a search engine: there are no parent selectors in CSS, not even in CSS3.
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
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")
};
if($(".myElem").parent().hasClass(".myDiv")) {
console.log("has a parent with the class .myDiv")
}
else
{
console.log("no parent class .myDiv found")
}
This should select those elements that have got class myElem with a parent that has a class myDiv:
$(".myElem").filter(function(elem) {
return $(this).parents(".myDiv").length
});
or this should select those elements that have got class myElem and does not have a parent that has a class myDiv:
$(".myElem").filter(function(elem) {
return !$(this).parents(".myDiv").length
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With