If Image 'Src' Is '(Unknown)' Replace with 'Missing. Png'

If Image 'Src' Is '(Unknown)' Replace with 'Missing. Png'

My CMS produces an img src="(unknown)" if an image isn't provided in the database. I would like to use javascript when this occurs to change it to img src="/images/missing.png" As a complete JS noob I have tried several hacks but none seem to work... any ideas? (there is likely to be more than one image on the page if that makes any difference)

2

4 Answers

This should work for you, if you use onError event for handling missing image src

<img src="main_img.png" onError="this.onerror=null;this.src='/images/missing.png';" />
0

I used this to solve a similar problem I had (using javascript)...

const images = document.querySelectorAll("img");

images.forEach((image) => {
  let imgsrc = image.getAttribute("src");
  if (imgsrc === "") {
    image.src = "/images/missing.png";
  }
});

if you're using php then this problem is going happen for sure you can use esc_url($url)

esc_url function solves the problem

If you're dynamically injecting the src when the page loads, you can always check and swap with placeholder if needed.

if (imgSrc === "unknown") {
    imgSrc = "placeholder.png";
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.