0

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.

1
  • How about bind the event to $('#menu a') and then just do alert($(this).attr('id'))? Commented Sep 9, 2010 at 3:55

4 Answers 4

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

If you want the id, then do

$('#menu a').click(function(){
    alert($(this).attr('id'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.