Hijibiji
Hijibiji

Reputation: 458

Change part of background-image: url with jQuery

I had to shift the image resources of my website to under a new domain. So all the image links are broken. For the images however, I have changed the src with jQuery using the following function below.

$(document).ready(function () {
    $('img').each(function () {
        var src = $(this).attr('src');;
        $(this).attr('src', src.replace('www.old', 'images.new'));
    });
});

But it works for the <img src=""> links only. I have some other images as the background of different div where this function doesn't work. Such as:

<div class="hero" style="background-image: url('https://www.old.com/image.jpg');"></div>

How can I change the part of this background-image: url('https://www.old to background-image: url('https://images.new with jQuery?

Upvotes: 1

Views: 441

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29277

You can target all the elements with the style background-image and includes the old path and replace their background-image src using .css().

$(document).ready(function() {
  $('img').each(function() {
    var src = $(this).attr('src');;
    $(this).attr('src', src.replace('www.old', 'images.new'));
  });

  $('[style*="www.old.com"]').each(function() {
    $(this).css('background-image', function(i, old) {
      return old.replace('www.old', 'images.new')
    });
  });
});

https://jsbin.com/kuceqes/edit?html,js,console

Upvotes: 1

Related Questions