Charles Yeung Charles Yeung - 1 year ago 61
HTML Question

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

I have a requirement to add the

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


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

After (exclude ".jpg"):

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

Answer Source

In jQuery:

$(document).ready(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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download