Aneesh
Aneesh

Reputation: 1733

Get id of enclosing li tag

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

Answers (4)

user1253034
user1253034

Reputation:

JSFiddle demo

$('a').on('click',function(){
    alert($(this).parent('li').attr('id'));         
});  

Upvotes: 0

zzlalani
zzlalani

Reputation: 24344

Try

$('a').click(function () {
   var li = $(this).parent();
   var li_id = li.attr('id');
});

Fiddle: http://jsfiddle.net/zugdB/

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272006

Use this line inside your click handler:

var id = $(this).closest("li").attr("id")

Upvotes: 2

Try

fiddle Demo

var li_id = $('a').filter(function () {
    return $(this).text() === 'click me ';
}).parent().attr('id');

or

fiddle Demo

var li_id =$('a:contains("click me")').parent().attr('id');

var li_id = $(this).parent().attr("id")

Upvotes: 1

Related Questions