jQuery closest exclude self

后端 未结 4 1049
余生分开走
余生分开走 2020-12-29 18:15

closest() will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. But I want

相关标签:
4条回答
  • 2020-12-29 19:01

    Vanilla js:

    el.parentElement.closest('.container')
    

    Jquery:

    el.parent().closest('.container');
    
    0 讨论(0)
  • 2020-12-29 19:09

    If you truly want only parent divs, then yes $(this).parents('.container') would work. If you want to look for the closest element and allow for it to be a sibling (which it seems might be what you are actually trying to accomplish) you can use $(this).prev('.container').

    0 讨论(0)
  • You can traverse a level up before trying to find the .closest() ancestor:

    $(this).parent().closest('.container');
    
    0 讨论(0)
  • The right answer is .parents('.container:first'); thanks

    0 讨论(0)
提交回复
热议问题