tags:

views:

30

answers:

4

Hello,

My html:

<div id="menu"><ul><li>menu one<ul>
<li><a id="home">home</a></li>
<li><a id="contact">contact us</a></li>
</ul></li></ul></div>

Jquery :

    $('#menu').click(function(){
        alert($(this).find('a').attr('id'));
    });

I want to find value of a clicked. my code return empty.

+2  A: 
$('#menu a').click(function(){
    alert($(this).html());
});

If you want the id, then do

$('#menu a').click(function(){
    alert($(this).attr('id'));
});
Capt Otis
A: 

Your .find('a') will return multiple elements. If you want to display each of their values loop using .each(). Else do something like this: .find('a')[0].attr('id')

Looping code:

xxx.find('a').each( alert($(this).attr('id')); )

Sidharth Panwar
A: 

Your code works for me, it returns "home" every time as that's the first descendant a of the div. Perhaps you're looking something more like

  $('#menu a').click(function(){
        alert($(this).attr('id'));
  });​

Fiddle http://jsfiddle.net/rsbPt/

Robert
A: 

The reason why this won't work is because $(this).find('a') returns an array, thus you need to iterate over all of the anchors in #menu to obtain their id. You can do that with the .each() function:

$('#menu').click(function(){
  $(this).find('a').each(function(){ alert(this.id) });
});

Will give you two alert() for the HTML you gave, each with a different id. You can then replace the alert() with whatever function you need to perform on each of the anchors.

Yi Jiang