Reputation: 89
Im trying to figure out, on how to replace the folder path and not the img. The folder names are always the same, they're are not dynamic. If i click button "one", it should change all my images folder paths to "dist/one/", the same logics goes for the two others.
<button id="one" type="button">This should change the path to "dist/one/"</button>
<button id="two" type="button">This should change the path to "dist/two/"</button>
<button id="three" type="button">This should change the path to "dist/three/"</button>
<img src="dist/one/rocket.png" alt="" />
<img src="dist/two/rocket.png" alt="" />
<img src="dist/three/rocket.png" alt="" />
Upvotes: 0
Views: 988
Reputation: 26143
I'd use a data attribute for this. Store a template for the image src and a path value for each button, then update the image src values accordingly for each button click...
var buttons = document.querySelectorAll("button");
var images = document.querySelectorAll("img");
[].forEach.call(buttons, function(button) {
button.addEventListener("click", function() {
var path = this.getAttribute("data-path");
[].forEach.call(images, function(img) {
var src = img.getAttribute("data-src-template").replace("{path}", path);
img.src = src;
console.log(img.src);
});
});
});
// intialize the image...
document.querySelector("#one").click();
<button id="one" type="button" data-path="dist/one">This should change the path to "dist/one/"</button><br/>
<button id="two" type="button" data-path="dist/two">This should change the path to "dist/two/"</button><br/>
<button id="three" type="button" data-path="dist/three">This should change the path to "dist/three/"</button><br/>
<img data-src-template="{path}/rocket.png" alt="" />
<img data-src-template="{path}/rocket.png" alt="" />
<img data-src-template="{path}/rocket.png" alt="" />
This gives you what you need as well as being flexible if the path format ever changes, since everything you need is defined in the html and the script never needs to change.
For example, if you decided to move the images into another subfolder you could just change the image tag and it would still work...
<img data-src-template="newSubFolder/{path}/rocket.png" alt="" />
Upvotes: 2
Reputation: 23
I believe you can do that by creating script.
If you assign ID to each of the <img>
tags you can then do something like:
document.getElementById('exampleID').innerHTML="<src="new_path">";
Eventually put each <img>
tag in DIV
<div id=someid>
<img src="dist/one/rocket.png" alt="" />
</div>
Script:
document.getElementById('someid').innerHTML="<img src="new_path"/>";
I did not test it but the answer should be really close to this.
I hope this was helpfull.
Upvotes: 0