フリーランス|WEB 制作経験丸7年、制作会社様からのご依頼に丁寧・高クオリティでお手伝いいたします。 IRODORI DESIGN

B L O G

【jQuery】imgタグのalt属性の値を取得・変更・削除する方法

alt属性
jQuery
削除
取得
変更

この記事ではjQueryを使ってimgタグのalt属性の値を取得、変更、削除する方法をご紹介します。

alt属性の取得

jQueryを使ってimgタグのalt属性を取得する方法はこちら。

// alt属性の値を取得する
$(window).on('load',function(){
    let img_alt = $('img').attr('alt');
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

alt属性の変更

jQueryを使ってimgタグのalt属性を変更する方法はこちら。

// alt属性の値を変更する
$(window).on('load',function(){
    $('img').attr('alt','alt属性を変更しました');
    let change_img_alt = $('img').attr('alt');
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

alt属性の削除

jQueryを使ってimgタグのalt属性を削除する方法こちら。

方法1

// alt属性の値を空にする
$(window).on('load',function(){
    $('img').attr('alt','');
    let empty_img_alt = $('img').attr('alt');
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

方法2

// alt属性を削除する
$(window).on('load',function(){
    $('img').removeAttr('alt');
    let remove_img_alt = $('img').attr('alt');
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

方法1と方法2の違い

方法1と方法2はどちらもimgタグのalt属性を削除する指定ですが、それぞれの指定には違いがあります。

方法1の場合、imgタグは以下のようなコードになります。

<img src="xxx.jpg" alt>

alt属性自体は存在しているが、その値がなくなります。
また、jQueryで値を取得しても何も取得出来なくなります。

方法2の場合、imgタグは以下のようなコードになります。

<img src="xxx.jpg">

alt属性自体が無くなります。
また、jQueryで値を取得した場合、undefinedが返ってきます。

複数画像の場合

ここからは複数画像がある場合のそれぞれのalt属性の取得、変更、削除の方法をご紹介します。

alt属性の取得

jQueryを使って、複数あるimgタグのalt属性を取得する方法はこちら。

// alt属性の値を取得する
$(window).on('load',function(){
    $('img').each(function(index){
        let img_alt = $(this).attr('alt');
    });
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

alt属性の変更

jQueryを使って、複数あるimgタグのalt属性を変更する方法はこちら。

// alt属性の値を変更する
$(window).on('load',function(){
    $('img').each(function(index){
        $(this).attr('alt','変更画像' + index);
        let change_img_alt = $(this).attr('alt');
    });
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

alt属性の削除

jQueryを使って、複数あるimgタグのalt属性を削除する方法はこちら。

方法1

// alt属性の値を空にする
$(window).on('load',function(){
    $('img').each(function(index){
        $(this).attr('alt','');
        let empty_img_alt = $(this).attr('alt');
    });
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

方法2

// alt属性を削除する
$(window).on('load',function(){
    $('img').each(function(index){
        $(this).removeAttr('alt');
        let remove_img_alt = $(this).attr('alt');
    });
});

実装サンプルはこちら。

See the Pen Untitled by 寺井大樹 (@teraisan) on CodePen.

まとめ

いかがでしたか?
jQueryを使ってimgタグのalt属性の値を取得、変更、削除する方法のご紹介でした。