lgzambello lgzambello - 1 year ago 77
Javascript Question

document.getElementById(id) returns an object with all undefined variables

I have a series of canvas elements on my page that I used to make clocks. Each of these has many variables with default values- none of these variables are undefined at any point. (The following I am using as a variable example, but this is the case with all other variables as well.) The variable 'am' is false by default, unless I change it to true. Here is my first clock:

<canvas id="piechart0" width="200" height="200"></canvas>

I am trying to make it so that if 'piechart0.am == true', a button with an AM image appears, and if 'piechart0.pm == false' it disappears. However, when I do the following:

var clock = document.getElementById("piechart0");
var am = clock.am;
if (am) {

it correctly identifies clock as "canvas#piechart0", but both clock.am and the new var am are "undefined", rather than the either true or false the piechart0.am actually is equal to. Why are all of the variables coming out as undefined when the script is grabbing the correct element/what am I doing wrong here?

EDIT: Silly mistake, I was using a different class to keep track of variables that would dictate what I would draw onto the canvas. It is this class's variables I was trying to access, which is why canvas.am would show up as undefined. RESOLVED

Answer Source

The output is correct as it is.

clock variable is referring to the canvas HTML object. From what you've posted here, you haven't actually defined am attribute for that canvas. Thus, clock.am is undefined.

If you do

console.log("Should be the canvas object:: " + clock);
console.log("Did not define this, so it should output undefined:: " + clock.am);
console.log("Did define this as 200, so it should output 200:: " + clock.width);

you will see the width displayed but am will be undefined. Hope that's clear.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download