Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first href link of li in a ul list in jQuery

Tags:

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 :)

like image 505
topbennie Avatar asked Jan 05 '11 18:01

topbennie


2 Answers

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");
like image 148
Frédéric Hamidi Avatar answered Sep 21 '22 22:09

Frédéric Hamidi


$(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

like image 29
jAndy Avatar answered Sep 24 '22 22:09

jAndy