Okkahs
Okkahs

Reputation: 1

Getting an element of a html file from an external js file

I would like help with this problem, i have a file named, index.html, and a file named javascript.js. When i do document.getElementById("canvas"), and then try to change something like the width of the canvas, it gives me a null exception.

Html file

<html>
    <body>
        <canvas> </canvas>
        <script src="javascript.js"></script>
        <script>getCanvas.start();</script>
    </body>
</html>

JavaScript file

var canvas;
function getCanvas() {
    canvas = document.getElementById("canvas");
    canvas.width = 500;
}

At line 4, google chrome throws me the following error on the console. Uncaught TypeError: Cannot set the property 'width' of null.

A huge thanks to anybody who helps.

Upvotes: 0

Views: 1432

Answers (4)

giuseppe straziota
giuseppe straziota

Reputation: 443

Without changing your html, you can use it as such:

document.body.getElementsByTagName('canvas');

Upvotes: 0

Keyur Shah
Keyur Shah

Reputation: 536

document.getElementById("canvas");

This it self say get Element By ID and you didn't give set id.

Try This in your HTML:-

<canvas id="canvas"> </canvas>

Upvotes: 0

otajor
otajor

Reputation: 953

document.getElementById("canvas"); will get you the element which has the id of 'canvas'. Your canvas element does not have the id 'canvas'.

Solution:

<canvas id="canvas"> </canvas>

Upvotes: 0

Manish Parakhiya
Manish Parakhiya

Reputation: 3798

You have to specify id to canvas element

<canvas id="canvas"> </canvas>

Upvotes: 1

Related Questions