Check if img src tag is empty or null or undefined
P粉111227898
P粉111227898 2024-03-28 09:36:47
0
1
362

I'm taking JSON data and processing that data to insert it into the correct html tags. Sometimes JSON data contains no information or is simply not available. In the given example, src is empty or the kicker does not exist, which would give something like {} or undefined or '' or null at this line:

document.getElementById("placeholder_" + (k)).src = jsonData[i].src;

I looked for a solution on the board and tried it, but without success. Or maybe I don't understand the logic. Some examples that didn't work for me:

document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';

Or I checked this link:

JSON is sometimes undefined - how do I check?

This is my code snippet, I want to check if there is data(url) in jsonData[i].src. How can I do this? In the second part, src is empty, and in the third part, the kicker is missing. How to check?

var jsonData = [
    {
    src: 'https://www.w3schools.com/tags/img_girl.jpg',
    kicker: 'Kyiv',
    headline: 'Grief and defiance in city on first anniversary of war in Ukraine',
  },
  {
    src: '',
    kicker: 'Russia',
    headline: 'how can Ukraine win? And what is the feeling within Russia?',
  },
  {
    src: 'https://www.w3schools.com/tags/img_girl.jpg',
    
    headline: 'how can Ukraine win? And what is the feeling within Russia?',
  }
  ]
  
 $(document).ready(function () {
    var k = 1;
    //loop through json data and insert into corresponding divs
    for (var i = 0; i < jsonData.length; i++) {
        document.getElementById("placeholder_" + (k)).src = jsonData[i].src;
        document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].kicker;
        document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].headline;
        k = k + 1;
    }
    });

P粉111227898
P粉111227898

reply all(1)
P粉662614213
const imgElement = document.querySelector('img');
const imgSrc = imgElement.getAttribute('src');

if (!imgSrc || imgSrc.trim() === '') {
  console.log('Image src is empty, null or undefined');
} else {
  console.log('Image src is not empty');
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template