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.
jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
if ($elem.parents('.left').length) {
}
There are many ways to filter for element ancestors.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
Beware, closest()
method includes element itself while checking for selector.
Alternatively, if you have a unique selector matching the $elem
, e.g #myElem
, you can use:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
.parentClass #myElem { /* CSS property set */ }
You can use parents
method with specified .class
selector and check if any of them matches it:
if ($elem.parents('.left').length != 0) {
//someone has this class
}
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