• First link...">

    How to get the first href li link in ul list in jQuery

    I have the following list

    <ul class="tabs"> <li><a href="testlink.php">First link</a></li> <li><a href="testlink2.php">Second link</a></li> </ul> 

    I would like to capture href for the first link. This link should be in the var link, so I can use it to dynamically retrieve the contents of the page. Thanks for any help :)

    +6
    jquery
    source share
    3 answers

    You can use : first selector:

     var url = $("ul.tabs a:first").attr("href"); 

    Or : eq () selector:

     var url = $("ul.tabs a:eq(0)").attr("href"); 
    +5
    source share
     $(function() { var href = $('ul.tabs').find('a').slice(0,1).attr('href'); }); 

    This is pretty fast if you try to avoid Sizzle selectors after execution:

    http://jsperf.com/selector-sizzle-vs-methods

    +4
    source share

    just like

     var link = $(".tabs li:first a").attr("href"); 
    0
    source share

    All Articles