Related: one of my favourite code golfing tricks is named access on the Window object https://html.spec.whatwg.org/multipage/window-object.html#na... >: document.getElementById("result").textContent = "Why do it this way—"; document.querySelector("result").textContent = "—or even this way—"; result.textContent = "—when you can do it this way?"; Edit: adding another similar test to this page, window[`test${i}`] is tak…
Love this trick. It should be noted that the element is added to the window object as long as the id follows the syntax of a valid javascript variable (meaning no dashes).
1. It doesn’t need to be a valid JavaScript identifier, though if it isn’t you’ll need to use subscripting syntax to access it:
> document.body.id = "like-this";
> window["like-this"]
2. It’s not added to the window object; rather, property lookup on a window object falls back to looking up elements by ID if there is no such property: > typeof example
"undefined"
> document.body.id = "example";
> example
> example = "no longer an element";
> example
"no longer an element"
> delete example;
true
> example