Check if any ancestor has a class using jQuery

JavascriptJqueryHtmlJquery SelectorsJquery 1.7

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

if ($elem.parents('.left').length) {

}

Solution 2 - Javascript

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 */ }

Solution 3 - Javascript

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncrmpiccoView Question on Stackoverflow
Solution 1 - JavascriptAlexView Answer on Stackoverflow
Solution 2 - JavascriptA. WolffView Answer on Stackoverflow
Solution 3 - JavascriptIgor DymovView Answer on Stackoverflow