Reputation: 2044
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:
Upvotes: 1
Views: 1062
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>");
});
Upvotes: 3
Reputation: 66991
You need to go up to the .closest('.field-item')
then append your text.
Upvotes: 1