I am trying to replace an img path in jquery (injecting into a remote page)
replace example.com/thumbs
with ex
You need to update the attribute with the returned value for that you can use a callback function as the second argument in attr() method where the second argument holds the current attribute value.
$('img').attr('src', function(i, src){
return src.replace('thumbs', 'images');
});
The above method will iterate over the img
tags if there are multiple img
elements so you can avoid using each() method for iterating.
setTimeout(function() {
$('img').attr('src', function(i, src) {
return src.replace('thumbs', 'images');
});
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://img.pranavc.in/100?t=thumbs" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs1" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs2" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs3" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs4" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs5" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs6" alt="#" />
Look at this one, you wasn't setting src for an image.
$(function() {
$('img').each(function() {
$(this).attr('src', $(this).attr('src').replace('thumbs', 'imagessss')); console.log('New src: ' + $(this).attr('src'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/images/thumbs.png" />
Step 1: script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
Step 2:
$(document).ready(function(){
$('img').each(function() {
$(this).attr('src', $(this).attr('src').replace('thumbs', 'images'));
console.log('Latest image link ' + $(this).attr('src'));
});
});
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
This is what you wanna do:
var newPath = $("img").attr("src").replace("thumbs", "images");
$("img").attr("src",newPath);
This gets the value, but doesn't set it back to the attribute:
$("img").attr("src").replace("thumbs", "images");
That requires another step, something like:
var newSrc = $("img").attr("src").replace("thumbs", "images");
$("img").attr("src", newSrc);
Or, if you want a single line:
$("img").attr("src", $("img").attr("src").replace("thumbs", "images"));