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?

3
  • 1
    var layer = "OMG WTF"; alert(layer.innerHTML) Commented Jan 23, 2013 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." stackoverflow.com/questions/3434278/… Commented Jan 23, 2013 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
    Commented Feb 16, 2021 at 19:32

3 Answers 3

19

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'].

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

1
  • 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
    Commented Feb 16, 2021 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.