Xarcell
Xarcell

Reputation: 2011

Replace Text In Background Image URL

Simplified, I have this structure:

<div id="RelatedPosts1">
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div>
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-2.jpg)"></div>
    <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-3.jpg)"></div>
</div>

I wish to replace the "s72-c" with "s320". Thus, changing the size of the image.

This is what I tried with jQuery:

<!-- Let's replace low-res with a higher-res -->
$(".related-posts-thumb").text(function () {
    return $(this).text().replace("s72-c", "s320"); 
});

I'm guessing this didn't work because the image URL isn't "inside" the element. So I'm not sure how to achieve my desired effect. I'm not a javascript/jQuery expert and I haven't seen any examples addressing anything similar to what I'm trying to do.

Upvotes: 1

Views: 171

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

You could use the .css() method with the function parameter option

$('.related-posts-thumb').css("background-image",function(idx,current){
    return current.replace('s72-c','s320');         
 });

Upvotes: 1

Colin Schoen
Colin Schoen

Reputation: 2592

Not really sure when you want this to trigger, so I'll just make this an on click...

 $('.related-posts-thumb').each(function() {
     $(this).attr("style", $(this).attr("style").replace("s72-c", "s320"));
 });

JSFiddle example (click on the background):

http://jsfiddle.net/wdc6ydtk/1/

Upvotes: 1

Related Questions