Test if links are external with JavaScript

1
2
3
4
5
6
7
8
9
10
var internalLinkPattern = new RegExp(location.host);
var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
var link = links[i];
internalLinkPattern.test(link.href) ?
link.setAttribute('data-target', 'internal') :
link.setAttribute('data-target', 'external');
}
0%