Web production note

 【更新日 :

【脱Jquery】JavaScriptでhttpから始まる外部リンクにtarget blankを追加する。

Category:
JavaScript

JavaScriptでhttpから始まる外部リンクにtarget blankを追加する機能を実装したサンプルです。

codepen

See the Pen add target blank Vanilla JS by web_nak (@web_walking_nak) on CodePen.

JavaScript

//外部リンクにtarget blankを追加する
const httpLinks = Array.prototype.slice.call(document.querySelectorAll('a[href^=http]'),0);
if(httpLinks.length) {
  //サイトのホスト名を取得
  const hostname = location.hostname;
  httpLinks.forEach(function(elm){
    //ホスト名が異なるリンク設定の場合のみ_blank系の設定を追加
    if(elm.getAttribute('href').indexOf(hostname) === -1) {
      elm.setAttribute('target','_blank');
      elm.setAttribute('rel','noreferrer noopener');
    }
  });
}

classも追加する場合

//外部リンクにtarget blankを追加する
const httpLinks = Array.prototype.slice.call(document.querySelectorAll('a[href^=http]'),0);
if(httpLinks.length) {
  //サイトのホスト名を取得
  const hostname = location.hostname;
  httpLinks.forEach(function(elm){
    //ホスト名が異なるリンク設定の場合のみ_blank系の設定を追加
    if(elm.getAttribute('href').indexOf(hostname) === -1) {
      elm.setAttribute('target','_blank');
      elm.setAttribute('rel','noreferrer noopener');
      //class追加
      elm.classList.add('is-blank');
    }
  });
}

関連リンク