views:

26

answers:

4

I have this markup (simplified):

<ul class="targets">
    <li><a href="javascript:void(0);" class="info">A</a></li>
    <li><a href="javascript:void(0);" class="info">B</a></li>
    <li><a href="javascript:void(0);" class="info">C</a></li>
</ul>

And this script (simplified):

$('.targets').click(function(e) {
    alert(e.target); // alerts "javascript:void(0);"
});

What I really want is the clicked anchor object, not the target for the anchor.

If this is possible, how do I do it?

It must be anchors in the list, but the function must handle clicks on other dom elements as well.

A: 
$('.targets li a.info').click(function(e) {
    alert(this);     // alerts the anchor DOM object itself
    alert(e.target); // alerts "javascript:void(0);" <- this *should* do the same
});
Tomalak
Forgot to mention, It has to work with other elements than anchors as well. Is it possible?
Mickel
@Mickel: Sure, it works with any element that you bind the function to. Instead of working with `e.target`, use `this` directly, as indicated.
Tomalak
A: 

It's not doing what you think it's doing; e.target is definitely your <a> element. Try changing it to alert(e.target.className) to prove it to yourself.

Pointy
A: 
$('.targets li a').click(function(e) {
    alert(this.attr('href'));
});

the keyword "this" as a jQuery reference to the element at hand

RobertPitt
+3  A: 

I think your confusion comes from the e.target toString being the href property, for example:

$('.targets').click(function(e) {
  alert(e.target.nodeName); // alerts "A"
  $(e.target).fadeOut();    //this would fade out the anchor you clicked on
})​;

e.target is what you already have, you just need to access whatever property you're interested in on it. Otherwise when you alert it, by default it shows the href property.

Here's a demo to see what I mean

Nick Craver
Ah! Of course :) Thanks Nick.
Mickel