1

I was wondering how to do something like this without needing the ():

let start = () => document.getElementById("#start");

currently i use it like this:

start().classList.remove("hidden");

but i would like to use it like this:

start.classList.remove("hidden");

but it should still call the function. How do I do this?

0brine
  • 450
  • 5
  • 18
  • 2
    "*but it should still call the function.*" sounds like you're having a problem with defining the variable too early. The whole "needing to call the function without ()" sounds like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – VLAZ Nov 14 '20 at 23:40

1 Answers1

0

I don't think there are any good ways to do this, but there are a few ugly and not recommended ways.

  • You could rely on the fact that DOM elements with IDs automatically become global variables, and not use getElementById at all:

    start.classList.remove("hidden");
    
  • You could make window.start a getter:

Object.defineProperty(window, 'start', { get() { return document.getElementById("start"); } });

start.classList.remove("hidden");
.hidden {
  display: none;
}
<div id="start" class="hidden">foo</div>
  • You could use with and a getter (please don't do this):

with ({
  get start() { return document.getElementById("start"); }
}) {
  start.classList.remove("hidden");
}
.hidden {
  display: none;
}
<div id="start" class="hidden">foo</div>

If start happened to be part of an object, rather than referencing it as a standalone variable, putting a getter on the object would be a much more reasonable solution:

const domElements = {
  get start() { return document.getElementById("start"); }
};
domElements.start.classList.remove("hidden");
.hidden {
  display: none;
}
<div id="start" class="hidden">foo</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It (1) requires global pollution (which is inelegant and can lead to bugs) (2) is somewhat unintuitive - a script reader normally wouldn't expect simply *referencing* an identifier to possibly result in side-effects (like the running of arbitrary code) – CertainPerformance Nov 14 '20 at 23:47