Solve - Cannot set property 'src' of Null in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Cannot set property 'src' of Null #

The "Cannot set property 'src' of null" error occurs for 2 reasons:

  1. Setting the src property on a null value (image element that doesn't exist).
  2. Inserting the JS script tag above the HTML, where the DOM elements are declared.

cannot set property src of null

Here is an example of how the error occurs.

index.js
const image = null; // ❌ Cannot set properties of null (setting 'src') image.src = 'photo.jpg';

To solve the "Cannot set property 'src' of null" error, make sure that the image element you're setting the src property on exists. The error most commonly occurs if you use the getElementById() method and pass it an id that is not present in the DOM.

index.js
const image = document.getElementById('does-not-exist'); console.log(image); // 👉️ null // ❌ Cannot set properties of null (setting 'src') image.src = 'photo.jpg';
In the example, an image with the provided id does not exist in the DOM, so the getElementById method returns a null value. When we try to set the src property on a null value, the error occurs.

Another common reason for getting the error is placing the JS script tag before declaring the DOM elements.

To solve the "Cannot set property 'src' of null" error, make sure that the JS script tag is placed at the bottom of the body, after the HTML elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ❌ BAD - script is ran before img is created ❌ --> <script src="index.js"></script> <img id="photo" width="200" height="200" src="cat.jpg" /> </body> </html>

Notice that the JS script tag is placed above the code that creates the img element. The index.js file is ran before the img element is created, therefore we can't access the img from inside the index.js file.

index.js
const image = document.getElementById('photo'); console.log(image); // 👉️ null // ❌ Cannot set properties of null (setting 'src') image.src = 'photo.jpg';

The JS script tag should be moved to the bottom of the body tag, after all of the DOM elements it needs access to.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <img id="photo" width="200" height="200" src="cat.jpg" /> <!-- ✅ GOOD - img already exists ✅ --> <script src="index.js"></script> </body> </html>

Now the img element can be accessed from the index.js file.

index.js
const image = document.getElementById('photo'); console.log(image); // 👉️ img#photo // ✅ Works image.src = 'photo.jpg';

Conclusion #

The "Cannot set property 'src' of null" error occurs when:

  • trying to set the src property on a null value (an image element that doesn't exist in the DOM)
  • inserting the JS script tag before the DOM elements have been declared
Use the search field on my Home Page to filter through my more than 1,000 articles.