oompahloompah
oompahloompah

Reputation: 9333

Jquery: How do I get the url of an anchor contained within a clicked 'li' tag?

The following is a segment of HTML in one of my pages:

<li class="prodcat-line">
   <a title="foobar" class="prodcat" href="/some/url.php">Foobar</a>
</li>

I want to be able to retrieve the url of the clicked on li tag. My "jQuery fu" IS NOT WHAT IT SHOULD BE. I know how to bind the click event of li elements of class "prodcat-line", but I don't know how to extract nested tags from within the clicked item - can anyone help?

Upvotes: 9

Views: 17154

Answers (5)

Yoann
Yoann

Reputation: 5077

Whan you click on th li tag you can have his child elements. Two way to do this.

$('.prodcat-line').click(function() {
    $(this).children('a').attr('href');
    //or
    $('a', this).attr('href');
});

Upvotes: 0

Mutation Person
Mutation Person

Reputation: 30498

If you select out the li like so

$(".prodcat-line")....

Then, you can either select direct descendents using '>':

$(".prodcat-line>a")....
$(".prodcat-line>a.prodcat")....
$(".prodcat-line>.prodcat")....

Or, using jQuery children method:

$(".prodcat-line").children("a")...
$(".prodcat-line").children("a.prodcat")...
$(".prodcat-line").children(".prodcat")...

Or from any descendent, omit the > and use just a space:

$(".prodcat-line a")....
$(".prodcat-line a.prodcat")....
$(".prodcat-line .prodcat")....

Or, again, using a jQuery method, this time find:

$(".prodcat-line").find("a")...
$(".prodcat-line").find("a.prodcat")...
$(".prodcat-line").find(".prodcat")...

Upvotes: 0

Arthur Halma
Arthur Halma

Reputation: 4001

$('.prodcat-line').click(function(){
    alert($('a', this).attr('href'));
    return false;
});

Example here.

Upvotes: 14

Hussein
Hussein

Reputation: 42818

$('a').click(function(e) {
    e.preventDefault();
    alert($(this).attr('href'));
});

Check working example at http://jsfiddle.net/4XU8h/

Upvotes: 2

nfechner
nfechner

Reputation: 17525

How about:

$('.prodcat').click(function(event) {
    var url = $(this).attr('href');
});

Since you only have the link within the LI, you don't need to reference the LI. Every click on the LI will target the link anyway.

Upvotes: 1

Related Questions