-1

I'm new to JavaScript and am having problems with changing an image on my html document. I know that in order to change images, I need to change the src attribute of the img.

I have an image called "magenta.jpg" that I want to replace with "fuschia.jpg" as soon as the page loads.

My HTML

<img src="magenta.jpg" name="photo" id="photo">

My JavaScript

document.getElementById("photo").src = "fuschia.jpg";

When I try doing this, I get an error that says:

Uncaught TypeError: Cannot set property 'src' of null

Could you please help me understand what is going wrong with the code, and how to fix it?

antigravityguy
  • 157
  • 1
  • 7

6 Answers6

5

It executed before DOM is loaded. To solve this you can either move the <script> to the bottom of the document or

Inside your .js file:
¯¯¯¯¯¯¯¯¯¯¯¯¯¯

window.onload = function(){
    document.getElementById("photo").src = "fuschia.jpg";
}

Or if you prefer jQuery:

$(function(){
    $("#photo").attr("src", "fuschia.jpg");
});
Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228
2

The problem seems to be you execute your script before the element is in the DOM, hence the null.

If you want to keep the script in a separate file, you may call your code on load :

window.onload = function(){
    document.getElementById("photo").src = "fuschia.jpg";
}
Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
1

If you include your external script in the head of your document, then the DOM won't be ready and your document.getElementById("photo") will return null. Make sure you include the script just before the closing tag (best practice for performance reasons).

<script src="yourfile.js"></script>
</body>
Fotiman
  • 111
  • 6
1

This is a working example of changing a photo that includes a happy baby.

<img src="https://upload.wikimedia.org/wikipedia/en/thumb/3/32/A_photo_of_an_8.5-week-old_baby_smiling.jpg/480px-A_photo_of_an_8.5-week-old_baby_smiling.jpg" name="photo" id="photo">
<input type="button" value="Click To Change" onclick="ChangePhoto();"/>

var ChangePhoto= function() {
    var newPicLocation = "https://upload.wikimedia.org/wikipedia/commons/6/6a/Happy_face_ball.jpg";
    document.getElementById("photo").src = newPicLocation;
};
Terrance
  • 11,381
  • 4
  • 51
  • 78
0

It can't find the element with id "photo". Presumably the element hasn't been loaded yet.

For more information about that check these questions:
How to check if an embedded SVG document is loaded in an html page?
$(document).ready equivalent without jQuery

or use jquery's $(document).ready

Community
  • 1
  • 1
Joren Van Severen
  • 1,869
  • 2
  • 19
  • 29
0

you can use this code inested of your code, its work!

in html file

<div id="photo">
     <img src="magenta.jpg" name="photo">
</div>

and in javascript file

var temp= document.getElementById("photo");
temp.innerHTML=" <img name="photo" src='fuschia.jpg'>";
SDWACW
  • 215
  • 2
  • 4
  • 13