JavaScript

.attrを使ってページ内リンクの指定文字列を含むaタグのtargetを「_blank」に変更する方法【jQuery】

jQueryの.attrを使ってページ内のaタグのターゲット(target属性)を全て「_blank」に変更する方法をご紹介します。

.attrを使ってページ内リンクの指定文字列を含むaタグのtargetを「_blank」に変更するJavaScriptの記述

※jquery.min.jsファイルを読み込みます。リンク(URL文字列)内に「/category/」文字列を含むaタグはターゲット(target)属性を「_blank」に設定してます。

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
     $("a[href^='/category/']").attr("target","_blank");
});
</script>

ページ内リンクの指定文字列を含むaタグのtargetを「_blank」に変更するHTMLの記述

<div class="clWrap">
    <h1>リンク(URL)から指定文字列を含むaタグのtarget属性を「_blank」に変更</h1>


<ul>
    <li class="cat-item cat-item-36"><a href="/category/css">css</a>
    </li>
    <li class="cat-item cat-item-2"><a href="/category/javascript">JavaScript</a>
    </li>
    <li class="cat-item cat-item-3"><a href="/category/jquery">jQuery</a>
    </li>
    <li class="cat-item cat-item-53"><a href="/category/php">PHP</a>
    </li>
</ul>


</div><!--/clWrap-->

jQueryの.attrでページ内のリンク(URL)から指定文字列を含むaタグのtarget属性を「_blank」に変更するデモページ

jQueryの.attrでページ内のリンク(URL)から指定文字列を含むaタグのtarget属性を「_blank」に変更するデモ

これを使えばページ数が多いサイト等はページ内よリンク属性を一斉に変更できそうです。
(aタグだけで無くても変更できそうですね)

 
※流用される場合は自己責任でお願いします。
 デモページタグ内のGoogleアナリティクスタグは流用しないで下さい。