1
votes

I am new to jQuery. I am trying to get image src and replace the src. I can get the image using the function mentioned below but i cannot get the src.

<div class="class1">

<a href="Link1"><img src="//abc.com/1.jpg"/></a>
<a href="Link2"><img src="//abc.com/2.jpg"/></a>
<a href="Link3"><img src="//abc.com/3.jpg"/></a>
<a href="Link4"><img src="//abc.com/4.jpg"/></a>
.
.
.
<a href="Linkn"><img src="//abc.com/n.jpg"/></a>

</div>

This function doesn't work but this is what i need to do. I would like to get the src and replace the .jpg at the end with -xyz.jpg for all the images.

'galleryImg': $(this).children('img') return the image but when i add .attr('src'), it stops working

function () {
var $gallery = $('.class1 a');
return $gallery.map(function () {
    return {
        'galleryLink': $(this).attr('href'),
        'galleryImg': $(this).children('img').attr('src').replace('.jpg','-xyz.jpg')
    };
});
}
1

1 Answers

2
votes

You are using attr() in a wrong way.

First, attr('src') will only retrieve the current value, after changing it, you have to use attr('src', newvalue) to set it.

Second, attr() will only work on the first element of the collection. If you have more than one elements, you can use an each() loop on them, or call attr() with a function that will run for every attribute value, and the returned value will be set as the attribute's new value.

Here is an example for the latter (and a little demo):

$('.class1').find('img').attr('src', function(i, val) {
    return val.replace(/\.jpg$/,'-xyz.jpg');
});

This is all explained in detail in the documentation, which I recommend you read.