Check if any ancestor has a class using jQuery

后端 未结 3 713
醉话见心
醉话见心 2020-12-07 11:06

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

相关标签:
3条回答
  • 2020-12-07 11:30

    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
    }
    
    0 讨论(0)
  • 2020-12-07 11:41
    if ($elem.parents('.left').length) {
    
    }
    
    0 讨论(0)
  • 2020-12-07 11:47

    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 */ }
    
    0 讨论(0)
提交回复
热议问题