views:

40

answers:

3

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

+2  A: 

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')
SLaks
Why was this downvoted?
SLaks
@SLaks dunno, I voted up
Gandalf StormCrow
A: 

It looks fine to me, though, since you're only traveling one level up, you only need .parent(), not .parents() ... but best might be .closest() (you can read up on it here).

D_N
+3  A: 

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 (".").

nickf
Excellent catch! I just tested in FF and failed to notice how the IDs were constructed.
atxryan
@nickf not working nickf .. I added underscore same again ..
Gandalf StormCrow
`"ID and NAME tokens must begin with a letter ([A-Za-z])"`
nickf