Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'getAttribute' of null

Tags:

javascript

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>
like image 578
fiddletag Avatar asked Sep 12 '15 18:09

fiddletag


3 Answers

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.

like image 81
Asons Avatar answered Sep 30 '22 16:09

Asons


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.

like image 28
Fr0zenFyr Avatar answered Sep 30 '22 18:09

Fr0zenFyr


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');
like image 27
IT Vlogs Avatar answered Sep 30 '22 16:09

IT Vlogs