Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
352 views
in Web Development by 20 36 42
edited by

In my website, I want to check if the alt attribute for all images has not been set or an empty string and give it a default value.

How to set the alt attribute value of an img tag?


1 Answer

1 like 0 dislike
by 20 36 42
edited by

To set the alt attribute value of an image

1 ) In JavaScript

<script type="text/javascript">

var imageTag = document.getElementsByTagName('img');

 for (var i = 0; i < imageTag.length; i++) {
 if (imageTag[i].alt == "" || imageTag[i].alt == null) {
            imageTag[i].setAttribute("alt", "your defualt text");
   }
}
</script>

2 ) In JQuery

<!-- reference jQuery link -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
$('img').each(function () {
 const alt = $(this).attr('alt'); //Get the alt value
       if (!alt) {
            $(this).attr('alt', 'your default text'); //Set your desired alt text
         }
    });
});
</script>

3) Optimize jQuery script, to reduce the need for an explicit loop and make the code simpler

$(document).ready(function () {

$('img[alt=""], img:not([alt])').attr('alt', 'default alt text');

});

If you don’t ask, the answer is always NO!
...