I just started learning JavaScript. I just want to build an image carousel but I get an error at my first line:
Uncaught TypeError: Cannot read property 'getAttribute' of null
js:
function changeImage(){
var imageSrc=document.getElementById("image").getAttribute("src");
}
changeImage();
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hello.js"></script>
<title></title>
</head>
<body>
<div id="button_left">
<img id ="left" src="left.png">
</div>
<div id="button_right">
<img id ="right" src="right.png">
</div>
<div class="container">
<img id ="image" src="1.jpg">
</div>
<div id="result"></div>
</body>
</html>
The error occurs because the "image" object is not yet loaded when the method gets called.
You need to run the "changeImage()" method after DOM is load, like in the body onload event,
<body onload="changeImage();">
or you add the script tag last in the body making sure the image object is loaded.
The problem is because document.getElementById("image")
in your script is called even before the targetted element is loaded which returns undefined
/null
. And then the chained .getAttribute("src")
is called on an undefined
/null
object.
One of the many possible solutions is to execute the function after page loads. Change the code in your script to below:
window.onload = function () {
var imageSrc=document.getElementById("image").getAttribute("src");
}
in hello.js
will make the script execute after the page has loaded completely.
Other answers cover several other ways to approach this.
Try this way:
var imageSrc = document.querySelectorAll('image[id=your-image-id]')[0].getAttributeNode("src").value;
Or use jQuery:
var imageSrc = $('image[id="your-image-id"]').attr('src');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With