1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.