Reputation: 1
I am trying to insert a link at the end of each .item
.
Everything is working fine but I get 7 printouts of the link after each element.
How can I get just the relevant link to print after each of it's .item
?
Thank you so much!
$('#content .item img').each(function(i) {
var altText = $(this).attr("alt");
$('<br /><a href="' + altText + '">visit website</a>').insertAfter('.imagefield');
});
Upvotes: 0
Views: 87
Reputation: 32367
You're calling insertAfter('.imagefield')
which will find all .imagefield elements and insert a link after them - for each image. Try insertAfter(this)
.
Upvotes: 0
Reputation: 101604
Change your selector to only find #content .item
, not the images within. Presumably you're iterating over any nested images within .item
(which would appear to be 7)
Remember that each will find all matches for the selector. If you're intent is only to work with .item
, then you need to be specific and only select .item
(not nested elements).
With no HTML in front of me, I would recommend:
$('#content .item').each(function(i,e){
$(e).append('<br /><a href="' + $('img',e).attr('alt')+ '">visit website</a>');
});
Upvotes: 2