Reputation: 27583
Given the following HTML:
<html>
<head>
<link href="http://example.com/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.
Upvotes: 0
Views: 3740
Reputation: 227280
You 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];
Upvotes: 6
Reputation: 3206
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 attributeUpvotes: 4
Reputation: 146310
Well with jQuery I would do:
var link_href = $('link', 'head').attr('href');
Upvotes: 2