gespinha
gespinha

Reputation: 8487

moving steps up in the DOM

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>

Upvotes: 0

Views: 96

Answers (2)

Christian Ternus
Christian Ternus

Reputation: 8492

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.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

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();

Upvotes: 2

Related Questions