Reputation: 1733
I have a HTML structure as follow. I've attached a jquery function to fire when click me
is clicked. From the function , I need to get the id of the the enclosing li
element. Is this possible? How?
<ul>
<li id="20">
<a href="#">click me </a>
</li>
</ul>
Upvotes: 0
Views: 126
Reputation:
$('a').on('click',function(){
alert($(this).parent('li').attr('id'));
});
Upvotes: 0
Reputation: 24344
Try
$('a').click(function () {
var li = $(this).parent();
var li_id = li.attr('id');
});
Fiddle: http://jsfiddle.net/zugdB/
Upvotes: 1
Reputation: 272006
Use this line inside your click handler:
var id = $(this).closest("li").attr("id")
Upvotes: 2
Reputation: 57105
Try
var li_id = $('a').filter(function () {
return $(this).text() === 'click me ';
}).parent().attr('id');
or
var li_id =$('a:contains("click me")').parent().attr('id');
var li_id = $(this).parent().attr("id")
Upvotes: 1