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.
$("ul li").click(function(event){
$("input").val($(this).html());
});
<ul>
<li><a href="http://www.google.com" id="google">Google</a>
</ul>
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements. Here selector is the selected element whose children are going to be found.
You can use the event. target to determine what was clicked: $('#daddy'). click(function (e) { alert(e.target.id); // The id of the clicked element });
jQuery children() Method The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
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
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 :)
You could use the children
method:
$(this).children('a').eq(0).attr('id');
I'm not sure about the syntax, but something like this should work.
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