【jQuery】imgタグのalt属性の値を取得・変更・削除する方法
この記事では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
属性の値を取得、変更、削除する方法のご紹介でした。