17

Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?

I recently discovered that I can use in javascript any object from DOM with a direct reference to its id:

<div id="layer">IM A LAYER</div>
<script>
   alert(layer.innerHTML);
</script>

If this is true, what advantage I'd get using the getElementById method?

Community
  • 1
  • 1
Alkarod
  • 173
  • 1
  • 4
  • 1
    `var layer = "OMG WTF"; alert(layer.innerHTML)` – Oleg V. Volkov Jan 23 '13 at 11:04
  • "This is doubly bad in that now you have to avoid naming your elements after any member of either the document or the window object you (or any other library code in your project) might want to use." http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here?lq=1 – Matt Zeunert Jan 23 '13 at 11:05
  • This problem is not specific to element id but has to with the global scope of variables. This is very easily coped with whne specifically scoping variables, which can be dealed with by scoping with function() {}(); – theking2 Feb 16 '21 at 19:32

3 Answers3

18

Accessing a DOM element directly will give you a error if the element does not exist. Wheras if you use getElementById it will return NULL.

You also can't access all elements directly if they, for example, have dashes in their name (some-id), because JS variables can't contain dashes. You could however access tthem with window['some-id'].

2540625
  • 11,022
  • 8
  • 52
  • 58
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
6

for example, if in your page you have elsewhere another previous script with

<script>
var layer = false; // or any other assignment
</script>

layer will be a reference to window.layer, then layer.innerHTML will fail. With document.getElementById you will avoid this tricky errors

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • getElementById when an element with that id will get just as tricky an error condision (undefined) as direclty accessing. Just lik the OP I don't see a the trickyness here. Please proof me wrong. – theking2 Feb 16 '21 at 19:28
1

This will work only for id's containing letters allowed for variable names. For id's like text-11, or item-key-21 it won't work.

techfoobar
  • 65,616
  • 14
  • 114
  • 135