Search code examples
javascripthtmlimageerror-handlingvariable-declaration

Cannot set property 'src' of null when using variable source


I saw that this question was asked many times and I've been looking in every single one for a solution but couldn't find one for my specific problem. I'm composing a link using different strings and variables and I would like to fill in a table with images. So far, in most of the threads that tackle this problem, I can see the following strategy:

document.getElementById('ID').src = variablewithlink;

or even this:

document.querySelector('img').src = variablewithlink;   

Inserted in the html as:

<img id="ID" src="" width="100" height="70";/>  

And that's what I used in my code, but it still gives

Uncaught TypeError: Cannot set property 'src' of null

When I'm logging the variable using alert, it shows the links that contain the images, but when reading it in the <img> tag, it gives that error. Can anyone help me figure out what I am doing wrong? The code is given below:

<html>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
  <script>
    var config = {
      apiKey: "AIzaSyCg9wsEL5tAYdSyz9IapqvvMGWpFNAlc74",
      authDomain: "checkup-7b62e.firebaseapp.com",
      databaseURL: "https://checkup-7b62e.firebaseio.com",
      projectId: "checkup-7b62e",
      storageBucket: "checkup-7b62e.appspot.com",
      messagingSenderId: "324802643995"
    };
    firebase.initializeApp(config);
  </script>

  <head>
  </head>
  <table style="width:100%" id="ex-table">
    <tr id="tr">
      <th>Image</th>
      <th>Text</th>
  </table>

  <script>
    var database = firebase.database();
    database.ref("-Events").orderByKey().limitToLast(5).once('value', function(snapshot) {
      if (snapshot.exists()) {
        content = '';
        snapshot.forEach(function(data) {
          val = data.val();
          link_for_picture = "https://firebasestorage.googleapis.com/v0/b/checkup-7b62e.appspot.com/o/" + val.imageUrl.split("/")[3] + "?alt=media";
          document.getElementById('image').src = link_for_picture;
          alert(link_for_picture);
          content += '<tr>';
          content += '<td>' + '<img id="image" src=link_for_picture border={0} height={150} width={150}></img>' + '</td>';
          content += '<td>' + val.headline + '</td>';
          content += '</tr>';
        });
        $('#ex-table').append(content);
      }
    });
  </script>

</body>

</html>


Solution

    1. You forgot to concatenate variable <img id="image" src='+link_for_picture+' border={0}. Using template literals will prevent this kind of errors.
    2. You have that src of null error because you're trying to get to the element img before appending it to the HTML.
    3. Last and most common rookie mistake: in that loop you create multiple elements with same id. But id must be unique.

    Here is http://jsfiddle.net/Smollet92/dwx1mb4a/4/ (because SO snippet is giving script error for some reason)