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

后端 未结 13 2006
伪装坚强ぢ
伪装坚强ぢ 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:55

    Just add :eq() selector like this:

    $("#element").parents(":eq(2)")
    

    You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...

提交回复
热议问题