Reputation: 269
How can change a specific part of an image src using jQuery after the page is being loaded?
This is an example link,
<img src="https://example.com/73832d3c5fca_175x175_c0b~bn1v1.jpg">
I want to replace the b1n1v1
with bn1v1
after the page is being fully rendered.
This is what I have tried to do so far but it doesn't work.
$(document).ready(function() {
return $(this).text().replace("b1n1v1", "bn1v1");
});
Thank you!
Upvotes: 1
Views: 2802
Reputation: 4472
Loop each images and replace the same .attr('src')
$(document).ready(function() {
$('img').each(function(){
$(this).attr('src',$(this).attr('src').replace("b1n1v1", "bn1v1"));
});
});
each https://api.jquery.com/each/
Upvotes: 4
Reputation: 337560
Your syntax isn't quite right as this
refers to the window
and return
is redundant at that point.
To make this work for all img
elements in the page you need to loop through them. To do that you can provide a function to attr()
which accepts the current value as an argument and returns the new value. Try this:
$(document).ready(function() {
$('img').attr('src', function(i, s) {
return s.replace("b1n1v1", "bn1v1");
});
});
Upvotes: 2
Reputation: 2655
Add a class to that image imageClass
.
$('.imageClass').attr('src').replace('bn1nv1', 'bn1v1');
Upvotes: 0