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

后端 未结 13 1926
伪装坚强ぢ
伪装坚强ぢ 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, ...

    0 讨论(0)
  • 2020-12-12 10:58

    Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

    $('#element').parents().eq(0);  // "Father".
    $('#element').parents().eq(2);  // "Great-grandfather".
    
    0 讨论(0)
  • 2020-12-12 10:58

    A faster way is to use javascript directly, eg.

    var parent = $(innerdiv.get(0).parentNode.parentNode.parentNode);
    

    This runs significantly faster on my browser than chaining jQuery .parent() calls.

    See: http://jsperf.com/jquery-get-3rd-level-parent

    0 讨论(0)
  • 2020-12-12 10:58

    If you plan on reusing this functionality, the optimal solution is to make a jQuery plugin:

    (function($){
    $.fn.nthParent = function(n){
      var $p = $(this);
      while ( n-- >= 0 )
      {
        $p = $p.parent();
      }
      return $p;
    };
    }(jQuery));
    

    Of course, you may want to extend it to allow for an optional selector and other such things.

    One note: this uses a 0 based index for parents, so nthParent(0) is the same as calling parent(). If you'd rather have 1 based indexing, use n-- > 0

    0 讨论(0)
  • 2020-12-12 10:58

    If you have a common parent div you can use parentsUntil() link

    eg: $('#element').parentsUntil('.commonClass')

    Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).

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