0

I was reviewing some code and thought I had found an error in relation to a missing getElementById in the JavaScript code. However, the output appeared to be in order. Working backwards I found this

With HTML code as follows;

<canvas id="display" width="600" height="600"></canvas>
<div id="stage" width="100" height="200"> </div>
<canvas id="hud" width="200"> </canvas>

..and JavaScript as below;

console.log(display.width); // displays 600
console.log(stage.width); // displays undefined as expected
console.log(hud.width); // displays 200

Any Id against the canvas element seems to need no formal declaration for the JavaScript to be able to find it within the HTML.

Am I missing something well known here? I note even on W3Schools that there is usually a variable declared to refer to the element ID.

Thanks in advance.

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
Geejayz
  • 39
  • 4

1 Answers1

2

DOM elements with IDs are automatically accessible similarly to global variables.

See this related answer: https://stackoverflow.com/a/3434388/2862621

Community
  • 1
  • 1
Tom Bowers
  • 4,951
  • 3
  • 30
  • 43
  • 1
    Just to add to Tom's answer, the reason the div returns a width of `undefined` is because `width` is not a property of div. You don't define the width of a div like that. But in a canvas element you do define the property by adding `width="200"` in the HTML tag. – 1cgonza Sep 22 '15 at 13:18
  • OK, many thanks for the answers. I wasn't quite sure what to search against. All of the above is useful – Geejayz Sep 22 '15 at 13:23