Charles Yeung Charles Yeung - 5 months ago 15
HTML Question

Automatically adding the 'alt' attribute to every image on a page

I have a requirement to add the

alt
attribute to each of the images on each of my web pages. The problem is that there are hundreds of images on some of those web pages.

Can anyone suggest an approach using JavaScript or jQuery that, for each image on a page, copies the name of the image (minus the extension) to a new
alt
attribute?

Before:

<img src="android.jpg width="100" height="50" />


After (exclude ".jpg"):

<img src="android.jpg width="100" height="50" alt="android" />

Answer

In jQuery:

$(document).ready(function() {
  $('img').each(function(){
    var $img = $(this);
    var filename = $img.attr('src')
    $img.attr('alt', filename.substring(0, filename.lastIndexOf('.')));
  });
});

You could ask before if alt attribute doesn't already exist by adding:

var attr = $(this).attr('alt');
    if (typeof attr == typeof undefined || attr == false) {
Comments