topbennie
topbennie

Reputation: 149

How to get first href link of li in a 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 grab the href for the first link. This link needs to be in a var link so I can use it to dynamically retrieve a page content. Thanks for any help :)

Upvotes: 7

Views: 11592

Answers (3)

jAndy
jAndy

Reputation: 235962

$(function() {
    var href = $('ul.tabs').find('a').slice(0,1).attr('href');
});

This is pretty fast, if you're after performance try to avoid Sizzle selectors:

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

Upvotes: 5

RobertPitt
RobertPitt

Reputation: 57268

simple as

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

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

You can use the :first selector:

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

Or the :eq() selector:

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

Upvotes: 8

Related Questions