Neko
Neko

Reputation: 1129

How to append the proper attribute to a series of elements?

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?

Upvotes: 0

Views: 95

Answers (4)

kapa
kapa

Reputation: 78671

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);
    }
});

jsFiddle Demo

For a little explanation:

  1. .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.

  2. this here will refer to the img that is currently used

  3. .closest() will return the closest parent of the image that matches the selector 'li'.

Upvotes: 3

Andy
Andy

Reputation: 30135

var $imgs = $('.page-template-default .gallery img');
$imgs.each(function($img) {
   if ($img.attr('alt') !== undefined) {
      $img.after("<small>" + $img.attr('alt') + "</small>");
   }
});

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

You need to iterate through each img if you want to use properties of each one like this.

var $imgs = $('.page-template-default .gallery li > a > img');
$imgs.each(function() {
   var $img = $(this);
   if ($img.attr('alt') !== undefined) {
      var $li = $img.parent().parent();
      $li.append("<small>" + $img.attr('alt') + "</small>");
   }
});

Upvotes: 0

Ēriks Daliba
Ēriks Daliba

Reputation: 718

$('.page-template-default .gallery img').each(function(i,it) {

  if ($(this).attr('alt') !== undefined) {

     var li = $('.page-template-default .gallery li').get(i);
     $( li ).append("<small>" + $(this).attr('alt') + "</small>");
  }

});

Upvotes: 0

Related Questions