How do I get the n-th level parent of an element in jQuery?

后端 未结 13 2001
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 10:24

When I want to get, for example, the 3rd level parent of the element I must write $(\'#element\').parent().parent().parent() Is there a more optimal method for

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 10:59

    Didn't find any answer using closest() and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
    You can use the closest() function combined with selectors to get the first element that matches when traversing upwards from the element:

    ('#element').closest('div')    // returns the innermost 'div' in its parents
    ('#element').closest('.container')    // returns innermost element with 'container' class among parents
    ('#element').closest('#foo')    // returns the closest parent with id 'foo'
    

提交回复
热议问题