Search code examples
javascripthtmlattributessetsrc

What is the problem with my Uncaught TypeError: Cannot set property 'src' of null


I have trying to change my code with .setAttribute too, the same thing appear..

In Javascript

document.getElementById("MyImg").src = "./sea.jpg";

In HTML :

<img src="./earth.jpg" id="MyImg">

Thank you for any futer answer !


Solution

  • Uncaught TypeError: Cannot set property 'src' of null

    The null is the important part. Your DOM search (getElementById) failed.

    Some ideas off the top of my head:

    1. The script is running in a different page
    2. The tag is not actually there
    3. There is a misspelling in the id (looks good in your example though)

    If you need an example to work off of: https://www.w3schools.com/jsref/prop_img_src.asp