12

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
  • 36,757
  • 12
  • 82
  • 99
Zo72
  • 13,873
  • 17
  • 69
  • 100
  • 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
  • @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

6

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
  • 857,932
  • 118
  • 1,152
  • 1,264
  • 4
    [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