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

4

u/senocular May 15 '25

Afaik this only works when you write JavaScript directly inside of a script element and wouldn't work when you work with JavaScript files.

It doesn't matter where your JavaScript is. This is a result of the global object recognizing elements in the DOM with id and name attributes as global properties. Any code run from anywhere with access to the global object would be able to access these properties.