5
votes

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>
5
you should move the script tag at the end of the body tag or run the code in hello.js on the onload event so it runs after the page is rendered. As it is now the page is not yet rendered when the code in hello.js is interpreted. - toskv

5 Answers

5
votes

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.

3
votes

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.

1
votes

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');
0
votes

Because you linked your JavaScript file in the head section of your HTML page. In this case, JS file loaded before HTML and JavaScript code cannot find a tag with id of image. So, write your script tag at the bottom of the HTML page.

-1
votes

The reason might be related to a missing name attribute in the img element.