Given the following HTML:
<html>
<head>
<link href="" rel="shortlink" />
</head>
<body></body>
</html>
How would I retrieve the contents of href="" in the link, rel=shortlink
with javascript? I don't know if such items in the head are accessible in the DOM.
The head-tag may contain more link-tags, for assets such as css. The head-tag may contain more then one link-shortlink (as per HTML5 'specs'), in that case, just pick the first.
Given the following HTML:
<html>
<head>
<link href="http://example./g/8c" rel="shortlink" />
</head>
<body></body>
</html>
How would I retrieve the contents of href="" in the link, rel=shortlink
with javascript? I don't know if such items in the head are accessible in the DOM.
The head-tag may contain more link-tags, for assets such as css. The head-tag may contain more then one link-shortlink (as per HTML5 'specs'), in that case, just pick the first.
Share Improve this question edited Dec 28, 2011 at 20:17 Charles 51.4k13 gold badges106 silver badges144 bronze badges asked Dec 28, 2011 at 20:14 berkesberkes 27.6k30 gold badges124 silver badges218 bronze badges 4- 1 Just curious, why do you want to do that? – Sergio Tulentsev Commented Dec 28, 2011 at 20:16
-
For "share/tweet this page" functionality, where I want to pass the self-defined shortlink, rather then the
document.URL
, which will be shortened with some arbitrary 3rd party shortner. – berkes Commented Dec 28, 2011 at 20:19 - Are you using jQuery? All the current answers seem to be jQuery. – gen_Eric Commented Dec 28, 2011 at 20:33
- 1 I have jQuery, but would rather write this specific function independent of jQuery, for portability reasons. – berkes Commented Dec 28, 2011 at 20:39
3 Answers
Reset to default 6You can use document.head
to get the head, and then use getElementsByTagName
to get the link
tags.
var links = document.head.getElementsByTagName('link');
for(var link in links){
if(links.hasOwnProperty(link)){
var l = links[link];
if(l.rel === 'shortlink'){
console.log(l.href);
}
}
}
NOTE: document.head
might not work in all browsers (by that, I mean it might not work in IE). If it's not working try this:
document.head = document.head || document.getElementsByTagName('head')[0];
I would do this with jQuery:
$('link[rel=shortlink]').eq(0).attr('href');
Where:
$('link[rel=shortlink]')
selects the appropriate elementseq(0)
selects the first of theseattr('href')
selects the appropriate attribute
Well with jQuery I would do:
var link_href = $('link', 'head').attr('href');