Setting target=“_blank” to external links

If you want your pages to be valid XHTML-Strict, but you also wish to open external links in new window, the following snippet is doing just that–sets attribute target=“_blank” to all external links in a document to keep your code valid XHTML-Strict. You’ll just have to change variable yourURL. Don’t enter http://www. part of your domain, otherwise something like will be treated like any other external link.

// change your domain name:
var yourURL = "";
function outLinks() {
  var outLink;
  if (document.getElementsByTagName('a')) {
    for (var i = 0; (outLink = document.getElementsByTagName('a')[i]); i++) {
      if (outLink.href.indexOf(yourURL) == -1) {
        outLink.setAttribute('target', '_blank');
window.onload = function() {

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?