3

How can I get the URL of a link?

$('.l').eq(0).href

is what I want to do, but it's undefined.


So given a jQuery selected anchor element, how do you get the href property?

Raj
  • 3,051
  • 6
  • 39
  • 57
Devin Rhode
  • 23,026
  • 8
  • 58
  • 72
  • 1
    http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery – sethobrien Aug 23 '11 at 07:00
  • Anchor elements don't have an href attribute, links do. – RobG Aug 23 '11 at 07:00
  • NO! You don't know and you are asking. Why could be stupid? – Soner Gönül Aug 23 '11 at 07:00
  • Just image you have this: `

    Foo

    `. Would the question make sense? That's why you need to post your HTML.
    – Álvaro González Aug 23 '11 at 07:00
  • @RobG, excuse me, could you proof your statement with some links to W3C? – Daniel O'Hara Aug 23 '11 at 07:02
  • Fill yer boots: [HTML attributes](http://www.w3.org/TR/html401/index/attributes.html). href applies to A, AREA, LINK, BASE. Read the specification for an [A element](http://www.w3.org/TR/html401/struct/links.html#edef-A). In short, an A with a href is a link. An A with no href and a name or id is an anchor. Also [DOM 2 HTML anchors](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-7577272) collecton and [links collection](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-7068919). – RobG Aug 23 '11 at 07:25
  • Lastly, there's the [HTMLAnchorElement](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-48250443) and [HTMLLinkElements](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-35143001).If it has an *href* that links to a resource, it's a link. If it has a *name* that's the target of a link, it's an anchor. It can have both *name* and *href* and so be both an anchor and a link. The OP is after links. – RobG Aug 23 '11 at 07:33

3 Answers3

7

Try:

$('.l').eq(0).attr("href")
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
0

Are you sure you're selecting the link? Because I'm trying this in my site and ir works just fine:

    $('#id')[0].href 

I mean, are you sure the $('.l').eq(0) part is working?

rafa
  • 326
  • 3
  • 9
0

I think this is what you're looking for $('.1 a')[0].href

Xeo
  • 357
  • 2
  • 11