Basically it’s a visibility problem. What happens if your id
is a property of the object window
? I don’t know if you know, all the properties you access globally or are in window
.
The question code is the same as:
window.a.innerHTML = 'CONTENT';
<div id="a"></div>
This is not standard. It’s something Internet Explorer started to do (putting DOM Ids inside the object window
), many programmer started using and other browsers felt "obligated" to maintain compatibility. But you can’t count on this.
Perform this:
top.innerHTML = 'CONTENT'; //top é uma propriedade de window
<div id="top"></div>
I put in the Github for future reference.
So in most cases it will work, but in some it won’t. Either because the implementation does not accept this form, or because it will confuse with something of the object. Isn’t it better to keep a style and use only one shape that will always work? Use the shape with getElementById()
which is standard, will always be supported in any DOM implementation as per the HTML/Ecmascript specification.
It was never intended to have this compact shape by accessing the ID directly. Although to tell you the truth, here’s a little opinion, I should allow it, but in the right way, no document
and not in the window
, and Ids are segregated into a specific property to avoid confusion with the object.
This technique is to give you a local object (I hope you are using a var
or let
) which is not confused with other properties.
I think they could have done something like this:
document.ids.a.innerHTML = 'CONTENT';
There are people who think that I wouldn’t even need all this and the id
Alone should already solve and the programmer to turn to if there is name conflict with some property. It makes some sense. It could even have a standard shape in the language, like using #top
not to be confused with top
.
I actually think it’s wrong window
be the object default. document
is what you use most.
I’ve always had that question, good question...
– MagicHat
Thanks @Magichat, really had never noticed before
– Miguel