JQuery: How to get the URL of the anchor contained in the 'li' tag?

The following is an HTML snippet on one of my pages:

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

I want to get the url of clicking on the li tag. My "jQuery fu" IS NOT SOMETHING TO BE. I know how to bind the click event from li elements of the prodcat-line class, but I don’t know how to extract nested tags from a clicked element - can anyone help?

+6
source share
5 answers
 $('.prodcat-line').click(function(){ alert($('a', this).attr('href')); return false; }); 

An example is here .

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

Check out the working example http://jsfiddle.net/4XU8h/

+2
source

What about:

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

Since you only have a link inside the LI, you do not need to reference the LI. Each click on LI will in any case be aimed at the link.

+1
source

If you chose li like this:

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

Then you can select direct descendants using '>':

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

Or using the jQuery children method:

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

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

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

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

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

When you click on the li tag, you can have its children. Two ways to do this.

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

Source: https://habr.com/ru/post/885631/


All Articles