Reputation: 481
I want to replace all svg images on my page with other svg images with the same name, but in a different directory. Specifically, the current images are in the img directory, I want to replace the source of the images to img/icon-black. I get all the svg elements with the following selector:
$.svgSelector = $(document).find('img[src$=".svg"]');
I calculate the new sources with the following:
var newSources = $.svgSelector.map(function(){return $(this).attr("src");}).get();
for(var i = 0; i < newSources.length; i++) {
newSources[i] = newSources[i].replace(/^.*[\\\/]/, '');
newSources[i] = "img/icon-black/" + newSources[i];
}
The problem arises when I want to assign the new sources to the individual elements in the selector.
I want to do something like this:
for(var j = 0; j < newSources.length; j++) {
$.svgSelector[i].attr("src", newSources[i]);
}
i.e. assign the source of each individual element's in the selector to its corresponding new source.
This way does not work, however. .attr() only returns the first src in the selector, and you cannot use it on individual elements of the selector like this either. I have also tried the .each() function but I cannot figure it out. How do I solve this?
Upvotes: 0
Views: 34
Reputation: 66133
Instead of having to map all the src
attributes to a new array, and then iterating through the array to replace the values, and then rewriting the sources in yet another loop, you can all do it in a single iterative block:
$.svgSelector = $(document).find('img[src$=".svg"]');
$.svgSelector.each(function() {
newImageSrc = "img/icon-black/" + $(this).attr('src').replace(/^.*[\\\/]/, '');
$(this).attr('src', newImageSrc);
});
Even better: the .attr()
function actually takes a callback. In that sense, you can even condense it further:
$(document).find('img[src$=".svg"]').attr('src', function(i, src) {
return "img/icon-black/" + src.replace(/^.*[\\\/]/, '');
});
Upvotes: 3