15

I noticed the following:

<div id='myDiv'>...</div>

<script>
    myDiv.style.color = 'red'; // I can access the object.
<script>

Before realizing this, I was always using the following:

var x = document.getElementById('myDiv'); 
x.style.color = 'red';

I am confused. What's the point of the second approach? Does the first approach always work?

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
Zo72
  • 14,593
  • 17
  • 71
  • 103
  • 1
    If I recall correctly the first approach only works on IE and with certain elements, the second is the correct and crossbrowser way to do it – frisco Apr 02 '13 at 15:24
  • I would guess that the second approach is actually compliant with the standards, and that the first is left over from a previous era and that you probably shouldn't rely on it always being the case. – Anthony Grist Apr 02 '13 at 15:24
  • With the second approach you can reuse your variable 'x' in various other scenarios easily. – Billy Moat Apr 02 '13 at 15:24
  • 1
    @frisco it works on Chrome. I am using chrome – Zo72 Apr 02 '13 at 15:24
  • I agree this is a duplicate question – Zo72 Apr 02 '13 at 15:26

1 Answers1

9

Are IDs for an html element always available from the window object?

No. It is a non-standard Microsoft-ism that some other browsers have adopted for compatibility reasons. It is prone to namespace collisions, and not completely cross-browser compatible: don't do it.

What's the point of the second approach?

It is standard, well-supported cross-browser (and also cross-language).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 8
    [HTML5 adds this behavior to the standard.](http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object) – josh3736 Aug 05 '15 at 00:39
  • I think it's good practice to use the same name for ids as my variables. Wouldn't the same namespace collision happen when I use getElementById? Why write that extra line if the result is the same and both has been supported for decades? – agiopnl Mar 07 '22 at 20:23
  • Was shocked to discover this today (it's 2022). It's called "Named access on the Window object", they mark it as "non-normative", and say: "As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use `document.getElementById()` or `document.querySelector()`." – Gilad Barner Aug 02 '22 at 14:27