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

后端 未结 13 1995
伪装坚强ぢ
伪装坚强ぢ 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 11:10

    Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

    E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

    var top = $("#Four").parents("#One"); alert($(top).html());

    Example using index:

    //First parent - 2 levels up from #Four
    // I.e Selects div#One
    var topTwo = $("#Four").parents().eq(2);
    
    alert($(topTwo ).html());
    

提交回复
热议问题