A little-known fact is that valid DOM element id attributes are exposed by the DOM into the JavaScript space as properties of the window (globalThis) object. This means an element such as:

id=”testDiv”>Hello, World!

Can be accessed as follows without the need to use document.querySelector(‘#testDiv’) or its older cousin document.getElementById(‘testDiv’).

console.log(testDiv.textContent); // “Hello, World!”

However, as is, this pollutes the global namespace and MDN cautions against using the id attribute this way primarily because of the potential conflict with other entities in the global namespace such as window properties. MDN advises using the aforementioned document methods.

When hand-crafting CSS, a long-lost art, the general (and sound) advice is to avoid using the id of an element to apply styling as this could be too specific. Personally, I have not had too much of an issue with styling by id but usually only in hobby projects and prototypes. In production code I usually stick with the guidance and would recommend the guidance to fellow frontend developers.

But, what if we could force the CSS issue whilst considerably reducing the potential of global namespace collision? Whilst testDiv is a valid CSS selection by id #testDiv, adding a dollar symbol to the front makes it invalid (#$testDiv is not a valid CSS selector).

At the same time, it is highly unlikely that the window API will acquire properties with such a prefix, reducing collision potential.

There are JS libraries (of old) that use the $ symbol, the most well-known of course being JQuery, and whilst there is a wealth of code out there in the wide using such libraries, I suspect they are now used anywhere near as much in production code these days.

In conclusion, using prefixing element id attributes with a dollar symbol would:

  1. Impede the use of the id in CSS styling, not that it is done very often these days.
  2. Enable JS to reference the DOM elements directly without the need to look up the element first using a document method such as querySelector or getElementById.
id=”$testDiv”>Hello, World!
console.log($testDiv.textContent); // “Hello, World!”

Is this a crazy idea? I would like to hear what others have to say in the comments below.