7

I'm trying to replace the default Yelp star rating image for businesses with one of my own. To do so I need to find the corresponding image source for each of the possible 5 images that could have loaded. And then, based on that I need to load in the proper image I've created.

<div id="starRating">
    <img src="http://yelp-star-1.png"/>
</div>

So, yelp-star-1.png would be replaced with my-star-1.png. So on and so forth. This is probably pretty simple, but I'm new to jQuery and everything I've found has not worked properly. Your expertise is very much appreciated!

David Hubler
  • 141
  • 1
  • 2
  • 9
  • Is there logic between the name of the file to be replaced and the replacement file name? – ChrisW Jun 21 '12 at 00:29
  • 1
    It sounds like you're trying to find what the Yelp score is to set what your image should be. If so, I think you need to look into their API: http://www.yelp.com/developers/documentation/v2/overview – Paul Sham Jun 21 '12 at 00:46

3 Answers3

14
$("#starRating img").attr("src", "http://pathto/my-star-1.png")

EDIT

I think that you're asking how to dynamically replace the src based on what is there currently. So if there is some direct difference in strings, maybe try

var img = $("#starRating img");
img.attr("src", img.attr("src").replace("yelp", "my"));
JeremyWeir
  • 23,396
  • 10
  • 89
  • 106
  • The tricky part for me is that I have to use either my-star-1, my-star-2, my-star-3, my-star-4 or my-star-5 based on the image that gets loaded from Yelp. I'm having a hard time knowing how to find the yelp image that loads so that I can replace it with the correct image. – David Hubler Jun 21 '12 at 00:31
  • 2
    Are you asking how to do string replacement? You aren't being very clear. – JeremyWeir Jun 21 '12 at 00:35
  • 1
    Sounds like he doesn't know the names of the yelp img files... Use firebug to inspect them? Or in fact most browsers now? – Jasper Mogg Jun 21 '12 at 01:06
5

If you are just trying to do a basic replace without any pattern:

$('img[src="http://website.com/images/yelp-star-1.png"]').attr('src','http://website.com/images/my-star-1.png');

This could be used with images who have a src attribute starting with http://website.com/images/yelp-star-

$('img[src^="http://website.com/images/yelp-star-"]').each(function() {
   $(this).attr('src', $(this).attr('src').replace("yelp", "my"));
});  
GrayB
  • 1,010
  • 8
  • 22
4

@GrayB gave me a good solution - this does not require you to know the absolute img src:

jQuery('.element img').each(function() {
    jQuery(this).attr('src', jQuery(this).attr('src').replace("find_", "replace_"));
}); 
Q Studio
  • 1,778
  • 3
  • 15
  • 17