How can I get the href of a <link> tag using jQuery?

Matt picture Matt · Mar 27, 2010 · Viewed 17.5k times · Source

I've seen lots on how to do this with an tag, and I have no problem doing it with that one, but I can't seem to retrieve the href attribute of a <link> tag.

Even trying to grab the link tag at all:

alert($("link").length);

Gives 0.

Any ideas?

Thanks,
Matt

Answer

macca1 picture macca1 · Mar 27, 2010

If $("link").length is returning 0, your selector isn't coming up with anything and there's no hope for getting the link at all.

You need a better selector. Maybe attack it by ID (#linkId) or by a particular class, etc. There's tons of selectors you can use:

http://api.jquery.com/category/selectors/

Your first step is to get the .length to show 1 though. Then from there .attr('href') will give you the link location.

Edit: Sorry, misinterpreted what you are going for. I was thinking you meant the anchor tag. Here's how I've successfully accessed a link tag:

var links = window.document.getElementsByTagName('link');
$(links).each(function() {
    $(this).attr('href')  // this is your href for the link tag in the loop
});