Reputation: 50
I've search the forum for why my img is null
when getElementById
is called, and I've moved the script below the img, but I am still getting the error that the image is null
.
Here is my code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="irimg" src="ir.bmp" alt="Video Stream" style="width:640px;height:480px;">
<script type="text/javascript">
function loadNextImage() {
// An image element for loading our next image
var ourImage = new Image();
// Setup the event handlers before setting the source
ourImage.onload = function() {
// Request the next frame
requestAnimationFrame(loadNextImage);
// Swap out the image element on the page with the new one
var oldImage = document.getElementById('irimg');
oldImage.parentElement.insertBefore(ourImage, oldImage);
oldImage.parentElement.removeChild(oldImage);
};
ourImage.onerror = function(){
// Something went wrong with this frame. Skip it and move on.
requestAnimationFrame(loadNextImage);
}
// Finally load the image
ourImage.src = "ir.bmp?" + new Date().getTime();
};
requestAnimationFrame(loadNextImage);
</script>
</body>
</html>
The error is occurs here:
var oldImage = document.getElementById('irimg');
oldImage.parentElement.insertBefore(ourImage, oldImage);
The error given by Chrome is Uncaught TypeError: Cannot read Property 'parentElement' of null
.
I'd appreciate help in understanding why it is null. Thanks.
Upvotes: 2
Views: 22730
Reputation: 4354
You're removing the image with that ID, and then next time your code comes through it can't find any image with that ID.
You need to set that ID on your new image that you're replacing the old one with.
like so
// An image element for loading our next image
var ourImage = new Image();
ourImage.id='irimg';
see: https://jsfiddle.net/9Lp1724v/
Upvotes: 3