FYI there is more to the HTML id attribute
• Reading time: 1 minute
I always used the HTML id attribute without asking myself why it must be unique within a document. I simply assumed it was the role of an id to be unique.
Mind you all, I stumbled on the mdn documentation page, and there is more to this simple attribute.
When you declare an id attribute, the HTML element on which it is attached is automatically exposed on the global window object.
This allows for quick access to this element from anywhere in your page.
// This
const element = document.getElementById("myElementId");
// Is equivalent to
const element = window.myElementId;The only caveat is name collisions: your ìd attribute value must be a valid JavaScript identifier and must not collide with existing properties on the window object.