I have multiple images with src URLs that all have
....content/..._gal6.jpg?format=100w
How can I use jQuery or JS to change all URLs to end with
?format=2500w
on click?
CodePudding user response:
Like this
document.querySelectorAll("img").forEach(img => {
const url = new URL(img.src);
if (url.searchParams.get("format")) {
url.searchParams.set("format", "2500w")
console.log(url.toString())
img.src = url.toString()
}
})
<img src="bla.jpg?format=250w">
<img src="bla.jpg">
<img src="bla.jpg?format=350w">
CodePudding user response:
Using Javascript:
Change the src property of the image:
function changeImage(){
document.getElementById('test-image').src = "https://url-to-second-image.com/image.png";
}
You can call the function using the click event in the html:
<img id="test-image" src="the-url/first_image.jpg" onclick="changeImage()">
Here is a jsfiddle: https://jsfiddle.net/f5mwext3/2/
The same way you can change only part of the name (I'm using whole external files for convenience)