tags:

views:

56

answers:

2

Thanks everyone for the help, rod.

Hi All,

I have a div that contains many spans and each of those spans contains a single href.

How do I attach a click event to the a tag?

Thanks, rodchar

+4  A: 

Your live selector would be div span a (an a somewhere inside a span that's somewhere inside a div). E.g.:

$('div span a').live('click', function() {
  // ...
});

If you want to limit it to only an a that's a direct child of a span which is a direct child of a div, that would be div > span > a (or div span > a for as that are direct children of spans anywhere in a div, etc.).

If you want to do this for just one specific div, replace div above with #the_id_of_the_div (or any other selector that will identify that specific div).

T.J. Crowder
+4  A: 

If there is a large number of anchors (a, or "hrefs" as the OP calls them) then this might be better to write using event delegation: attach a single click listener to the parent div and in the callback, find out which a originally fired the event.

$('#yourDiv').click(function (event)
{
    var $target = $(event.target);
    if($target.is('div>span>a')
    {
        // your callback logic here, where you can consider
        // $target to be analogous to $(this) in a non-delegated handler
    }
});
Matt Ball
++ wow, very nice way to handle that! but i think his problem is the preventDefault(), don't you?
meo
This is what the `.live` and `.delegate` methods do internally, no reason to implement it manually.
interjay
good to know! but he used click ;)
meo