Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get parent, parent id?

Tags:

jquery

<ul id ="myList"> <li><a href="www.example.com">link</a></li> </ul> 

How can I get the id of the ul (myList) using jQuery? My j-script event is triggered when the a link is clicked. I have tried:

$(this).parent().attr('id'); 

But it gets the id of the li, I need to go one higher, and I cant attach the click to the li either.

like image 934
panthro Avatar asked Apr 21 '12 16:04

panthro


People also ask

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How can get parent div id on button click?

parent() so $(this). parent() but this would get the parent div of the input.


2 Answers

$(this).parent().parent().attr('id'); 

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id'); 

Is a more foolproof solution for your case.

like image 113
Casey Foster Avatar answered Sep 22 '22 12:09

Casey Foster


 $(this).closest('ul').attr('id'); 
like image 43
abhijit Avatar answered Sep 24 '22 12:09

abhijit