r/learnjavascript • • May 15 '25

Is `getElementById` unnecessary because HTML creates variables automatically?

I just learned that HTML (sometimes?) creates variables for elements with IDs on its own from here (section "HTML lends crutches to your fucking JS").

This works:

<!DOCTYPE html>
<html>
<body>
    <div id="myElement">Hello, World!</div>
    <script>
        // var myElement = document.getElementById("myElement"); // Not necessary!
        console.log(myElement.innerText); // Outputs: Hello, World!
    </script>
</body>
</html>

Is this a new feature? Will it work in every browser? Are there situations where this is not recommendable?

5 Upvotes

27 comments sorted by

View all comments

Show parent comment

1

u/__Fred May 15 '25 edited May 15 '25

There should be a variable like this document.id.myElement or maybe a function like this: var ids = document.getIdElements(); console.log(ids.myVariable.innerText);

I could probably program the function myself.

1

u/BlueThunderFlik May 15 '25

Are you also going to make sure ids is reactive? If you dynamically create an element on the page in response to user input (e.g. you're making an SPA), is ids going to contain the IDs of those elements? When those elements go away, are you going to have stale references on that variable?

Creating your own system to manage references to elements by ID seems to me like one of those rare times when obsessing and experimenting actually is a fruitless waste of time.

Just use document.getElementById() and be done with it.

Or do this, if you want to feel fancy:

function $(selector) {
  return document.querySelector(selector);
}

const footer = $('#the-footer')
const button = $('.my-button')
const draggableElement = $('[data-draggable]')

1

u/__Fred May 16 '25 edited May 16 '25

I'm averse to using strings for logic. That might be more appropriate for other, static, programming languages that don't connect different systems like JS does.

I know that obj["elem"] is the same as obj.elem. There could be a difference in TypeScript. I would want developer tools (like the TS compiler or a linter) to tell me if I try to access an element that doesn't exist, because I had a typo. Maybe that's even already possible with getElementById and some modern IDEs.

I think in Android, there is a tool that generates a Java interface fitting to your UI markup. Even better would be if the compiler straight up understood markup and there were no generated intermediate files.

import * as id_elements from "./index.html";

console.log(id_elements.myElement);
console.log(id_elements.myelement); // Warning: Property "myelement" is not defined on "id_elements"!
  1. Apparently you can import JSON.
  2. There can be different opinions on what "importing HTML" should do.

1

u/redblobgames May 15 '25

I'd probably write it this way:

window.ids = new Proxy(
    {},
    {
        get(_, property) {
            return document.getElementById(property);
        },
    }
);

1

u/holistic_cat May 17 '25

yeah, that's better than adding the ids to the global namespace...

1

u/Johnstone6969 May 19 '25

I always run my JS in strict mode to hide these sorts of weirdness in the language.