Is there any way in jQuery to check if any parent, grand-parent, great-grand-parent has a class.
I have a markup structure that has left me doing this sort of thing in the code:
$(elem).parent().parent().parent().parent().hasClass('left')
However, for code readability i'd like to avoid this sort of thing. Is there any way to say "any parent/grandparent/great-grand-parent has this class"?
I am using jQuery 1.7.2.
There are many ways to filter for element ancestors.
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 you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
You can use
parents
method with specified.class
selector and check if any of them matches it: