-3

I read this Replacing background image using jQuery not working and quite a few other things but I'm having issues with this one.

I'm trying to find all divs/elements that contain a background-image: url();. IF they contain a background image with https://website.com/imagepath/image.jpg I want to remove the "https://website.com" piece and leave it as a local url only i.e. "/imagepath/image.jpg"

I'd like to do this in pure JS but I'm not opposed to jQuery

Brendan Jackson
  • 305
  • 1
  • 3
  • 13

1 Answers1

1

This would be incredibly taxing on performance and I would not recommend doing it this way.

You would have to go through every single element on the page and check its computed style and then update that if it matches your provided string.

const searchStr = 'https://website.com/imagepath/image.jpg';
const replaceStr = 'https://website.com/newimage.jpg';
const body = document.getElementsByTagName('body')[0];
const elements = Array.from(body.getElementsByTagName('*'));

elements.map(element => {
  const style = window.getComputedStyle(element);

  if (!!style.backgroundImage.includes(searchStr)) {
    element.style.backgroundImage = replaceStr;
  }
});
ChazUK
  • 744
  • 4
  • 26