I have this bit of code:
if ($('.page-template-default .gallery img').attr('alt') !== undefined) {
$('.page-template-default .gallery li').append("<small>" + $('.page .gallery img').attr('alt') + "</small>");
}
Basically it appends the alt text of an image next to the image itself.
Problem is, I have a page with 10 images and the appended alt text is always the same, taken from the first image.
Is there way to return each alt text to the respective image?
Seems to be the easiest way:
$('.page-template-default .gallery img').attr('alt', function (i, alt) {
if (typeof alt != 'undefined' && alt!='') {
$(this).closest('li').append(alt);
}
});
For a little explanation:
.attr()
can be used with a function as its second parameter. Normally it is used to set the attribute (this time alt
) using the return value of the function. In this one, I don't return anything, just use it to loop through the alt
attributes of the specified images.
this
here will refer to the img
that is currently used
.closest()
will return the closest parent of the image that matches the selector 'li'
.