Adding class to external links
Testing different methods for adding a class automatically to all external href links on page.
by mark47
HTML
<div><a href="foo.html">Internal</a><br />
<a href="http://fiddle.jshell.net/foo.html">Explicit Internal</a><br />
<a href="http://google.com">External</a><br />
<a href="mailto:[email protected]">Mailto</a></div>
CSS
.external {
color: red;
}
.external2 {
font-weight: bold;
}
JavaScript
// Method 1
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).addClass("external");
// Method 2
$.expr[':'].external2 = function(obj) {
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external2').addClass('external2');
// Method 3 - adds class to mailto links as well
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).addClass('external3');
}
});