Gandalf StormCrow
Gandalf StormCrow

Reputation: 26192

need help with jquery selector

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

Upvotes: 3

Views: 87

Answers (3)

SLaks
SLaks

Reputation: 887225

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')

Upvotes: 2

nickf
nickf

Reputation: 545985

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

Upvotes: 3

user241244
user241244

Reputation:

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

Upvotes: 0

Related Questions