Web production note

 【更新日 :

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

Category:
jQuery
Tags:

※jQueryを使わずjavascriptのみで実装したサンプルも公開しました。

指定した範囲の中でhttpから始まる外部リンクがあった場合に、aタグにtarget blankを追加するサンプルコードです。

JavaScript

//外部リンクblank設定
$('#hoge').find('a[href^=http]').not('[href*="'+location.hostname+'"]').attr({target:"_blank"});

classも追加する場合

//外部リンクblank設定 blankというclassも追加する
$('#hoge').find('a[href^=http]').not('[href*="'+location.hostname+'"]').addClass('blank').attr({target:"_blank"});

サイト全体に適応する場合

//外部リンクblank設定
$('a[href^=http]').not('[href*="'+location.hostname+'"]').not('[href*="mailto"]').attr({target:"_blank"});

関連リンク

参考リンク