0

Is there a way to move steps up in the DOM through JQuery or Javascript? (preferably JQuery)

To avoid doing a sequence of parent() tags, I should better use something that could sum something like this up:

$('.myElement').parent().parent().parent().fadeIn();

This should target the .final element in the following example:

<div class="final">
    <div>
       <div>
          <div class="myElement"></div>
       </div>
    </div>
</div>
gdoron
  • 147,333
  • 58
  • 291
  • 367
gespinha
  • 7,968
  • 16
  • 57
  • 91
  • 2
    there is no .final element – Arun P Johny Oct 23 '13 at 02:32
  • 1
    Your snippet does not include a `.final` element. But, assuming it's in the actual markup, try [`.closest('.final')`](http://api.jquery.com/closest/). – Jonathan Lonowski Oct 23 '13 at 02:32
  • 1
    Use a selector for whatever parent you want to get. For instance if the top div is in the body you can do `$('.myElement').parent('body div').fadeIn()`; – megawac Oct 23 '13 at 02:32
  • 1
    you can refer to this solution: http://stackoverflow.com/questions/7093659/how-do-i-get-the-n-th-level-parent-of-an-element-in-jquery – eggward Oct 23 '13 at 02:33
  • 1
    possible duplicate of [difference between jQuery parent() and closest() function](http://stackoverflow.com/questions/9193212/difference-between-jquery-parent-and-closest-function) – PW Kad Oct 23 '13 at 02:33
  • `$('.myElement').closest('.final').fadeIn();` – Arun P Johny Oct 23 '13 at 02:33

2 Answers2

2

Assuming .final is a ancestor element of the .myElement element, you can use .closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$('.myElement').closest('.final').fadeIn();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

That's what .parents() is for. To get the N+1th parent, do:

$(this).parents()[N])

For example, $(this).parents()[0] is the first parent.

Christian Ternus
  • 8,406
  • 24
  • 39