0

Assuming I have a theme switcher, and there're multiple images/icons

<img src="images/icons/icon-1.png">
<img src="images/icons/icon-2.png">
<img src="images/icons/icon-3.png">
<img src="images/icons/icon-4.png">

And also I have another set of these icons with a different color/path

<img src="images/icons/blue/icon-1.png">
<img src="images/icons/blue/icon-2.png">
<img src="images/icons/blue/icon-3.png">
<img src="images/icons/blue/icon-4.png">

the below jQuery code working perfectly when I click to change theme color for 'once'

$('img').attr('src', $('img').attr('src').replace('images/icons', 'images/icons/blue'));

If I clicked again to choose another color say 'red', the path become like this

<img src="images/icons/red/blue/icon-1.png">

while it's supposed to be like this

<img src="images/icons/red/icon-1.png">

how I can make 'replace method' to find & overwrite old path WITHOUT change file name 'icon-1.png' for example, as it's a dynamic icons.

Thanks in advance.

3 Answers 3

4

Is the name always the same? in that case you can use the following code

$('img').attr('src', function(i, src){
    return 'images/icons/blue/' + src.split("/").pop()
});
Sign up to request clarification or add additional context in comments.

Comments

2

You need to loop and replace the src of each element.

$('img').attr('src', function(i, src){
    return src.replace('images/icons', 'images/icons/blue')
});

When you use the getter version of .attr() it will return the attribute value of the first element in the matched element set, so the same value will get set for all elements.

Comments

2

Just get the filename from the source first, then rewrite the whole source. Assuming that you send as "theme" to changeTheme function, something from the following values: "images/icons", "images/icons/blue", "images/icons/red", etc. this will do the trick.

function changeTheme(theme) {
 var img=$(img);
 var filename=img.attr('src').split('/');
 filename=filename[filename.length-1];
 img.attr('src',theme+"/"+filename);
}

Or if you don't minde storing the file name as a data attribute to the image, you can change the second and third lines of the functions, with something along the lines of:

var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute

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.