Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery child of clicked element

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>
like image 838
Tom Avatar asked Dec 11 '08 13:12

Tom


People also ask

How to select child of this jQuery?

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.

How to check child element in jQuery?

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.

How do I know if my child's element is clicked?

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 });

How to get child div text in jQuery?

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.


3 Answers

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

like image 181
smoothdeveloper Avatar answered Oct 08 '22 19:10

smoothdeveloper


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

like image 20
Wayne Austin Avatar answered Oct 08 '22 21:10

Wayne Austin


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.

like image 36
mbillard Avatar answered Oct 08 '22 20:10

mbillard