I have a jQuery script that finds any href link with a .jpg or .png as the source, and prepends some extra span elements to link. It works well, however if I have more than one link on a page, the prepend is added multiple times.
For example a page with 3 links, the first a tag will prepend the span 3 times, the second a tag will prepend the span 2 times and the the third link will prepend the span once.
How do I get the span to prepend only once per a tag?
$(document).ready(function() {
$("#main_content_container a[href$='px.jpg'], #main_content_container a[href$='.png']").each(function() {
$(this).attr('rel','lightbox').addClass("gallerypic");
$(".gallerypic").prepend("<span><img src='/images/common/zoom_in.png'/></span>");
$(".gallerypic span").addClass("zoom-icon");
});
});
It looks to me like these two lines don’t really belong in your
.each()block:Try moving them after the
.each, like: