I have a following HTML :
<ul class="someclass">
<li id="1">
<button type="button" class="grey"></button>
</li>
<li id="2">
<button type="button" class="grey"></button>
</li>
<li id="44">
<button type="button" class="grey"></button>
</li>
<li id="54">
<button type="button" class="grey"></button>
</li>
</ul>
Now here is what I'm trying to accomplish with jquery :
When button is clicked to find out id of parent li, here is how I tried and failed:
$(".grey").live('click', function(){
alert($(this).parents("li").attr("id"));
alert($(this).parents("li:first").attr("id"));
});
Both give me null alerted, how can I do this ?
QUESTION UPDATE
Ah yes, I forgot to mention that this button element is not exactly in the li tag, its created on-the-fly when li is hovered, using append? I wrote this example just so you could get Idea what I'm trying
ANOTHER UPDATE :
When I try just $(this).closest("li"); I get [object Object] alerted but if I add attr("id"); I get null
I think it might be an issue with your id values: you're not allowed to use tokens which start with a number. IIRC, Firefox won't mind, but IE fails on it (as it should). Change the ids to have a prefix, eg: "item_44" and it should be ok.
Source: http://www.w3.org/TR/html4/types.html
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
It works for me. EDIT: But not in Internet Explorer. As others have mentioned, IDs cannot start with a number. You should probably use a different attribute instead.
The best way do do this is to call the closest method:
$(this).closest('li')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With