nimrod
nimrod

Reputation: 5732

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.

Upvotes: 10

Views: 55716

Answers (3)

Joseph
Joseph

Reputation: 119837

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

Upvotes: 10

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

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

Upvotes: 6

James Allardice
James Allardice

Reputation: 165971

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.

Upvotes: 29

Related Questions