14

Possible Duplicate:
document.getElementById(“someId”) Vs. someId

For example I have an element with id="mybox" attribute, is there any difference between calling it with document.getElementById('mybox') and mybox directly, as I see both work same in most browsers? The jsfiddle shows live example http://jsfiddle.net/usmanhalalit/TmS3k/

If there is no difference then why document.getElementById('mybox') is so popular, is it a bad practice to call mybox directly?

Community
  • 1
  • 1
Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
  • See also [are DOM tree elements global variables here?](http://stackoverflow.com/q/3434278/1048572) – Bergi Feb 10 '14 at 19:01

3 Answers3

21

Some browsers in some rendering modes will create a global variable for each element with an id.

It is non-standard, won't work everywhere and definitely can't be depended upon.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
6

They don't "both work the same". IE introduced making element ids into global variables, other browsers copied it to some extent but don't fully support it. It's considered a very bad idea, just don't do it.

RobG
  • 142,382
  • 31
  • 172
  • 209
4

mybox.value does not work in most cases. I believe IE is the only browser (and only some versions of it) that would support it. In my Firefox browser, I get mybox not defined error message in the console.

Aleks G
  • 56,435
  • 29
  • 168
  • 265