A little dab'll do ya
Code Snippets
Technique #1
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).addClass("external");
Technique #2
$.expr[':'].external = function(obj) {
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');
Technique #3
$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');
Technique #4
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
// This is an external link
}
});
Reference URL no longer works.
I guess the author took it down… sorry about that. I removed that link and added an additional technique.
Any info on which of these is optimal for performance? (I’m guessing not #4 heheh)
I actually have no idea, that would be good to know.
Why does #4 create a new regular expression object on every iteration of the loop? That’d be pretty slow, as it’d have to parse the regexp on every iteration. I think it’d be significantly faster to create one RegExp, before the loop starts.
This is great, but I\m new to jquery – so how do you use this code? I assume it goes int he head somewhere, and then have a css style for ‘external’ – but does it need script tags etc?
Do it with CSS:
a[href^="http://"]{ /*Style an external link here*/ }
Nice – but this wouldn’t work if you have a CMS system that uses absolute urls (I think WordPress does this?)
Can you use this CSS technique to insert this:
target=”_blank”
into the href tag? I want to find all external links on a page and open them in a separate window, not style them.
why not use document.domain rather than manually typing in the domain?