0

My code needs to capture the 'src' of an image in a variable. It then needs to insert this variable into a 'href' tag on a link which surrounds the image.

$('.fancybox-image-li img').each(function(test) {
    var test = $(this).attr("src");
    $('.fancybox-image-link').attr('href', ''+test+'');
});

Unfortunately what seems to be happening is the 'test' var is only getting the attribute of the last img and then inserting this into all the 'href' attributes.

Any ideas how I can get the variable to change per image.

0

4 Answers 4

1

Maybe you should do

$('.fancybox-image-li img').each(function(test) {

    var test = $(this).attr("src");
    // find the closest element with the class
    $( this ).closest('.fancybox-image-link').attr('href', ''+test+'');

});

Otherwise in each iteration you set the href of all $('.fancybox-image-link') to the current href attribute, thus getting alle the $('.fancybox-image-link') with the last href

Sign up to request clarification or add additional context in comments.

Comments

0

your link selector is not ok. This $('.fancybox-image-link') will select all links with that class so all of them will have the same href attribute.

You need a more specific selector for the link. Maybe try and use the parent element, if both the image and the link are contained in the same element.

Comments

0

You should be more specific with $('.fancybox-image-link') using selection method like child ... to $(this).

Comments

0

$('.fancybox-image-link') returns all of the elements with that class. You're essentially modifying all of them each loop iteration.

Instead, use .index() to select individual ones:

$('.fancybox-image-li img').each(function(index, value) {
    $('.fancybox-image-link').index(index).attr('href', $(this).attr("src"));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.