3

I've noticed this a really long time ago, but I never found any information as to why this is supported by browsers in the first place.

In every major browser, it is possible to refer to elements on the page by using their id as a global variable. This fiddle shows an example of how it works. You can also try this out yourself (on this page) by just opening your console and pasting footer in it (which will return the <div id="footer"> on this page), or if you want to try it on a browser without console, just run javascript:alert(footer) from your url bar, which should alert "[object HTMLDivElement]" or something similar.

I've tested this in Chrome, Firefox, Opera and even Internet Explorer, and in each of those browsers it seems to work. After searching for any standards about it though, I couldn't find anything.

My question is, why does this work in every single browser, and is this part of any standards? Or is this just core JavaScript?

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • It's not in any spec as far as I can tell, and it's news to me this works in Chrome. Does it? – John Dvorak Dec 28 '13 at 23:16
  • @JanDvorak It does. You can try it by opening the JSFiddle I linked, or running either of the further testing methods I've described. – Joeytje50 Dec 28 '13 at 23:17
  • really more about the DOM than just javascript – charlietfl Dec 28 '13 at 23:21
  • @StephenThomas, I think it's rather a duplicate of this one: http://stackoverflow.com/q/3434278/684229. joeytje50, did you copy the jsfiddle example from there? Looks exactly like that! – Tomas Dec 28 '13 at 23:29
  • @Tomas No I didn't. This seems like a simple way to show that it works though, so it would make sense if scripts that are designed to do exactly this would look alike. – Joeytje50 Dec 28 '13 at 23:33

2 Answers2

0

As noted in the link referenced in my comment, there is no standard. Rather, it's behavior that Internet Explorer implemented and other browsers copied for compatibility

Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
0

Its to do with the Document Object Model (DOM), which defines the logical structure of documents and the way a document is accessed and manipulated. it is not best practice and its better to use document.getElementById(); to avoid naming collisions etc.

Here is an example answer in response to this question previously.

Community
  • 1
  • 1
Robert
  • 2,222
  • 2
  • 21
  • 36