Danny Englander
Danny Englander

Reputation: 2044

Jquery- grabbing an image's alt tag content and adding as text (getting duplications)

I have a little script that takes an image's alt tag an adds it as text as such:

 $(".field-item a img").each(function(i, ele) {
          $(".field-item").append("<span>"+$(ele).attr("alt")+"</span>");
      });​

The issue I am having is I am getting duplication where every alt tag is added to every image as text. So for "image-1", image-1 and image-2 get added as text where I only want the corresponding alt tag added as text.

I tired using .closest() e.g.

$(".field-item").closest().append("<span>"+$(ele).attr("alt")+"</span>");

... but that did not seem to do the trick. I have fiddle here:

http://jsfiddle.net/6pAZE/4/

Upvotes: 1

Views: 1062

Answers (2)

Ram
Ram

Reputation: 144689

You can use the closest() method, currently you are selecting all the elements with class of field-item in each iteration, try the following:

 $(".field-item a img").each(function(i, ele) {
     var alt = this.alt;
     $(this).closest(".field-item").append("<span>"+alt+"</span>");
     // or $(this).after("<span>"+alt+"</span>");
 });

Fiddle

Upvotes: 3

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66991

You need to go up to the .closest('.field-item') then append your text.

http://jsfiddle.net/6pAZE/6/

Upvotes: 1

Related Questions