Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find nth parent of an element using jquery

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

like image 798
Rakhitha Nimesh Avatar asked Nov 18 '11 09:11

Rakhitha Nimesh


People also ask

How do I find a specific parent in jQuery?

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.

What is the difference between parent () and parents () methods in jQuery?

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.

Where can I find grandparents in jQuery?

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.

What is nth child in jQuery?

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.


1 Answers

You can use .parents() and .eq():

$('#element1').parents().eq(2); 

http://jsfiddle.net/infernalbadger/4YmYt/

like image 57
Richard Dalton Avatar answered Sep 29 '22 16:09

Richard Dalton