pgoriの怠惰なブログ

適当なことを適当に書いていく日記

すべての要素の属性を置換する

例)すべてのaタグのhref要素を置換する

<a href="http://hoge.co.jp/"></a>
<a href="http://hoge.co.jp/aaa/"></a>
<a href="http://hoge.co.jp/bbb/"></a>

となっていたとき

var debugUrl ="debug.local";

$(function(){
	$("a[href]").each(function(){ 
		$(this).attr("href", $(this).attr("href").replace("hoge.co.jp", debugUrl));
	});
});

■a[href]
href属性を持つすべてのa要素を指定
■each
for文で全件ぶんまわすような関数
■attr
属性を設定する関数
■replace
文字列置換する関数

■結果

<a href="http://debug.local/"></a>
<a href="http://debug.local/aaa/"></a>
<a href="http://debug.local/bbb/"></a>