简体   繁体   中英

Cannot change the src of an img in Javascript (Cannot set property 'src' of null)

I'm new to Javascript so please forgive me if this is a rather stupid question... anyways, I was trying to change the source of an image, but every time the same error message "Cannot set property 'src' of null" appears.

Here's the HTML:

<figure>
  <img class="dist-pic" src="images/rock1.png" id="pic-id">
  <figcaption>text</figcaption>
</figure>

In the js file I later need to change the variable distance to either show an alert or change the picture. However, after spending a few hours on this problem I cannot figure out where the mistake lies:

var distance = 1;

if (distance == 0) {

  alert('ALERT!');

} else if (distance == 1) {

  var distPic = document.getElementById('pic-id');
  distPic.src = 'images/rock2.png';
}

The "Cannot set property 'src' of null" comes for the very last line of the js code. I already looked up so many turorials and stuff, but I simply cannot find the mistake. Thanks in advance! <3

Just wrap your code in the DOMContentLoaded event to ensure HTML is ready.

 // This ensures the HTML (DOM) is ready to work with. document.addEventListener('DOMContentLoaded', () => { var distance = 1; if (distance == 0) { alert('ALERT!'); } else if (distance == 1) { var distPic = document.getElementById('pic-id'); distPic.src = 'images/rock2.png'; } }); 
 <figure> <img class="dist-pic" src="images/rock1.png" id="pic-id"> <figcaption>text</figcaption> </figure> 

A common mistake beginners make is learning when code gets executed and when it should get executed. There are multiple ways to decide when code should get executed.


Q: When does the JavaScript get executed?

A: When the block gets loaded.

The browser will execute a block of code once it has been loaded, so that is anything between <script> and </script> (without the src attribute) or when using <script src="..."></script>

There are multiple ways to choose when to execute a block of code, here are three of the most common ways to execute a block of code once the DOM is ready.


After the HTML

One way to decide when code should be executed is to place it after all the HTML has been rendered right before the closing body tag. This way all your html elements will be in the DOM and accessible to use.

<body>
  <div>
    <p>Hello</p>
  </div>
  <script>
    // Your JavaScript here
  </script>
</body>

As an event listener

The more popular way is to use an event listener to listen for when the DOM has loaded completely. This will assure that anything that was to be rendered at load time is available to you within the callback. This can be placed anywhere within the document or external script. Source

<head>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // Your JavaScript Here
    })
  </script>
</head>
<body>
  <div>
    <p>Hello</p>
  </div>
</body>

As a deferer

A newer way to run the code is to use a deferer, this is only available on script tags that contain a src . This will tell the script to load after the DOM has rendered. This will also ensure that the DOM is loaded as with the previous methods. Source

<script src="/path/to/file.js" defer>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM