Reputation: 1199
I have loads of divs with the class "chicken" and these all have a unique inline background-image style applied to them, I want to be able to add a "@2x" to the BG image immediately before the .jpg ending - so an example would be - the div looks like this:
<div class="chicken" style="background-image: url('example.jpg');">
And I would like to be able to add "@2x" to make it become:
<div class="chicken" style="background-image: url('[email protected]');">
Note: I have loads of divs, so the image name is always different...
e.g.
<div class="chicken" style="background-image: url('[email protected]');">
<div class="chicken" style="background-image: url('[email protected]');">
<div class="chicken" style="background-image: url('[email protected]');">
<div class="chicken" style="background-image: url('[email protected]');">
<div class="chicken" style="background-image: url('[email protected]');">
So need a way to add the "@2x" before the ".jpg" on each of the divs Any ideas?
Upvotes: 1
Views: 101
Reputation: 167250
You can do like this using .each()
:
$('.chicken').each(function () {
$(this).css('background-image', $(this).css('background-image').replace(".jpg", "@2x.jpg"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chicken" style="background-image: url('monkey.jpg');"></div>
<div class="chicken" style="background-image: url('donkey.jpg');"></div>
<div class="chicken" style="background-image: url('kitten.jpg');"></div>
<div class="chicken" style="background-image: url('lollol.jpg');"></div>
This effectively works:
Upvotes: 4