Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent <li> item with jQuery

I am trying to get the parent <li> when I click on a specific <li> item.

http://jsfiddle.net/doonot/GjbZk/

So let's say I click on submodule 1, I get the clicked ID with $(this).attr('id'); How can I now get the ID of the parent <li> which is in this case module 1?

Please note that my tree is quite big, so it has to be flexible.

Thanks a lot, much appreciate your answer.

like image 874
nimrod Avatar asked May 04 '12 08:05

nimrod


2 Answers

You can use the closest method to get the first ancestor that matches a selector:

var li = $(this).closest("li");

From the jQuery docs:

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

like image 124
James Allardice Avatar answered Oct 18 '22 13:10

James Allardice


var parentModule = $('this')             //the selector of your span
    .parents('li:eq(1)')                 //get the next li parent, not the direct li
    .children('.rightclickarea:first')   //get the first element, which would be the span
    .attr('id')                          //get the span id
like image 43
Joseph Avatar answered Oct 18 '22 14:10

Joseph