Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically open external links in new tab or window.
// vanilla JavaScript
var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
// or in jQuery
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
@collinanderson

This comment has been minimized.

Copy link

@collinanderson collinanderson commented May 13, 2019

beautiful. you should probably add something links[i].rel = 'noopener'; too

@alancwoo

This comment has been minimized.

Copy link

@alancwoo alancwoo commented Nov 17, 2020

Quick ES6 version:

let links = [...document.links].forEach((link) => {
  if (link.hostname != window.location.hostname) {
    link.target = '_blank'
  }
})
@OliverBalfour

This comment has been minimized.

Copy link

@OliverBalfour OliverBalfour commented Jan 23, 2021

Or just:

[...document.links].forEach(link => {
  if (link.hostname != window.location.hostname)
    link.target = '_blank'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment