Question

I am attempting to create a function using jQuery that appends a copyright message to the end of all alt tags. So <img src="image.jpg" alt="this is alt text"> would end up <img src="image.jpg" alt="this is alt text - Copyright (c) John Doe">.

This is the function I created but it's not working:

$(document).ready(function() {
    $("img").each(function() {
        $img.attr("alt").append(" - Copyright (c) John Doe");
    });
});

Can anyone see what's wrong?

Was it helpful?

Solution

DEMO

$(document).ready(function() {
    $("img").each(function() {
        $(this).attr('alt',$(this).attr('alt')+" - Copyright (c) John Doe");
    });
});

$(this) refers to the current image in each loop.

$(this).attr('alt') get's the current attribute alt

$(this).attr('alt','value') this is how you assign value to the alt attribute

$(this).attr('alt',$(this).attr('alt')+" - Copyright (c) John Doe"); so code here replace the current with current + " - Copyright (c) John Doe"

Errors in your code

$img is not defined.

append deals with adding html contents to the element not the attribute

OTHER TIPS

$(document).ready(function() {
    $("img").each(function() {
        $(this).attr("alt",function(i,alt){
             return alt + " - Copyright (c) John Doe";
        })
    });
});

You would only use append to add something to an HTML element. Not an attribute. You can do this to append to an attribute. There's no reason for the each using this method.

$('img').attr('alt', function( idx, originalAlt ){
  return originalAlt + ' - Copyright (c) John Doe'
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top