I want to find the nth parent element of an given element and access the attributes of parent.
<div id='parent1'><br/> <div id='parent2'><br/> <span><p id='element1'>Test</p></span><br/> </div><br/> <div id='parent3'><br/> <span><p id='element2'>Test</p></span><br/> </div><br/> </div>
I want to access the 3rd parent element of element1 without using
$('#element1').parent().parent().parent()
Any help would be appreciated
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.
jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.
Definition and Usage. The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.
You can use .parents()
and .eq()
:
$('#element1').parents().eq(2);
http://jsfiddle.net/infernalbadger/4YmYt/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With