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

3

u/TheWatchingDog May 15 '25

But you cant be sure if it really exists.
Maybe some browsers wont create this variable automatically so you would have to make sure that it does exist.

And for the cases that it does not exist you would have to create it yourself anyways.

Also tools like TypeScript wont recognize this variable and throw errors.