views:

9714

answers:

3

Hi,

I've got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element I'd need google retuned.

I've tried '$this a' but can't quite work out the syntax.

jQuery:

$("ul li").click(function(event){
$("input").val($(this).html());     
  }
);



html:
<ul>
    <li><a href="http://www.google.com" id="google">Google</a>
</ul>
+5  A: 

I don't see the sample HTML but

$(this).find('a:first').attr('id')

would do it (fix a:first selector if it's not what you meant)

this refer to the element that fired your event

smoothdeveloper
I was just blind :)
smoothdeveloper
Thank you kindly :)
Tom
Yep, this is definitely it.
Josh
can I propose: jQuery(this).find('a:first').attr('id') ? I just run on a conflict in a project with prototype.
dimitris mistriotis
A: 

You could use the children method:

$(this).children('a')[0].attr('id');

I'm not sure about the syntax, but something like this should work.

GoodEnough
using the array indexer gives you a dom object back therefore the .attr method would not exist and error. U need $(this).children('a')[0].id or $(this).children('a').get(0).id or $(this).children('a').attr('id');
redsquare
Are you sure it returns a DOM object? Either way, I said I wasn't sure, I'll test it sometime and correct it if it's wrong.
GoodEnough
+2  A: 

Hey Tom

To make your code a little neater, lets bind triggers with functions like so: (i suggest you give your UL an ID so it is specific to only elements within that UL)

$('ul li').bind('click', getAnchorId);

The function that is called (getAnchorId) gets the ID attribute of the children element (a) of the clicked element (ul li) and applies it to a variable (anchorId), and to show its getting the correct info I put the result in an alert.

function getAnchorId() {
    var anchorId = $(this).children('a').attr('id');
    alert(anchorId);
}

Now u can do what ever u wish with that variable :)

hope this helps :)

Wayne Austin
That is highly subjective, I personally prefer to use an anonymous function, especially since this is so specific.
Pim Jager
agreed, and using bind is just extra key press effort instead of using .click.
redsquare